嘿伙计们,我是 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> )}})}谢谢
1 回答
幕布斯7119047
TA贡献1794条经验 获得超8个赞
好吧,看来您正在尝试在获得结果之前从帖子中进行渲染。您可以将渲染代码更改为
{appState.posts && appState.posts.results && appState.posts.results.map((post) => {
return (
<div key={post.id}>
<h5>{post.title}</h5>
</div>
)}
})}
添加回答
举报
0/150
提交
取消