类型错误:无法读取未定义的属性“地图”。反应 js

嘿伙计们,我是 React js 的新手,我收到了这个错误TypeError: Cannot read property 'map' of undefined,我尝试了对象的 console.log 并且它显示了所有结果但是我无法在浏览器中显示它,因为弹出这个错误。可能是什么原因?


const search = 'api/posts/search'

const [appState, setAppState] = useState({

    search: '',

    posts: [],

});


const [error, setError] = useState('')


useEffect(() => {

    axiosInstance.get(search + '/' + window.location.search)

        .then((res) => {

            const allPosts = res.data;

            setAppState({ posts: allPosts });

            setError('');

            // console.log(res.data);

        })

        .catch((errors) => {

            setAppState({});

            setError('Something went wrong!')

        })

}, [setAppState])





{/* console.log(appState.posts.results) */}

{appState.posts && appState.posts.results.map((post) => {

      return (

               <div key={post.id}>

                  <h5>{post.title}</h5>

               </div>

      )}

})}

谢谢


米琪卡哇伊
浏览 123回答 1
1回答

幕布斯7119047

好吧,看来您正在尝试在获得结果之前从帖子中进行渲染。您可以将渲染代码更改为{appState.posts && appState.posts.results && appState.posts.results.map((post) => {&nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<div key={post.id}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <h5>{post.title}</h5>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</div>&nbsp; &nbsp; &nbsp; )}})}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript