【问题标题】:TypeError: Cannot read property 'map' of undefined. React jsTypeError:无法读取未定义的属性“地图”。反应js
【发布时间】: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 &amp;&amp; 根本没有帮助)但没有有一个@ 987654328@ 道具(因此 .map 未定义,根据错误)。目前尚不清楚这是否与您从 API 中获得的内容相符。
  • appState.posts.results ,结果是因为我使用后端的分页,因为它是如何来自后端的。像这样{count: 1, next: null, previous: null, results: Array(1)}
  • 因为它是一个数组,但真正的值是一个对象。所以要么它应该是例如{ results: [] },或null/undefined

标签: javascript reactjs react-router jsx


【解决方案1】:

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

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

【讨论】:

  • 是的,这是完美的。按预期工作。非常感谢!
猜你喜欢
  • 2020-04-04
  • 1970-01-01
  • 2021-12-02
  • 2020-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
相关资源
最近更新 更多