TypeError:无法读取未定义的属性“ map”。 React JS

时间:2020-10-18 15:41:54

标签: javascript reactjs react-router jsx

嗨,我是新来响应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 个答案:

答案 0 :(得分:1)

好吧,您似乎正在尝试从帖子中进行渲染,然后再获得结果。您可以将渲染代码更改为

{appState.posts && appState.posts.results && appState.posts.results.map((post) => {
      return (
               <div key={post.id}>
                  <h5>{post.title}</h5>
               </div>
      )}
})}