[英]TypeError: Cannot read property 'map' of undefined. React js
嘿伙计们,我是响应 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>
)}
})}
谢谢
好吧,您似乎正在尝试在获得结果之前从帖子中进行渲染。 您可以将渲染代码更改为
{appState.posts && appState.posts.results && appState.posts.results.map((post) => {
return (
<div key={post.id}>
<h5>{post.title}</h5>
</div>
)}
})}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.