【发布时间】:2021-02-01 12:17:57
【问题描述】:
大家好,我是反应 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>
)}
})}
谢谢
【问题讨论】:
-
console.log(appState.posts.results)记录了什么? -
它显示来自后端的正确结果。像这样
0: {id: 11, title: "The previous demo of this website", post_date: "2020-10-14T22:43:31.217511+02:00",…} -
您最初的
appState.posts是[],这是真的(所以检查appState.posts &&根本没有帮助)但没有有一个@ 987654328@ 道具(因此.map未定义,根据错误)。目前尚不清楚这是否与您从 API 中获得的内容相符。 -
appState.posts.results,结果是因为我使用后端的分页,因为它是如何来自后端的。像这样{count: 1, next: null, previous: null, results: Array(1)} -
因为它是一个数组,但真正的值是一个对象。所以要么它应该是例如
{ results: [] },或null/undefined。
标签: javascript reactjs react-router jsx