在 React 子组件中异步检索状态有问题

Having issues with retrieving state asynchronously in React child component

我在 只有一个 嵌套子项中从我的 React 应用程序的状态中检索和显示信息时遇到了一个非常有趣的问题。

我正在尝试做的与此类似react-router tutorial for recursive paths。我有一个 Admin 路由,它将用户带到用户可以编辑的嵌套部分。我成功地将 props 传递给每个组件,呈现应用程序状态中保存的信息,直到达到某个点。

我的URL是:/admin/label/posts/edit/:post

我的组件如下所示:

import React from 'react'
import { withRouter } from 'react-router-dom'

const EditingPost = props => {
  const index = props.match.params.post
  const post = props.posts[index]
  return(
    <div>
      {post.title}
    </div>
  )
}

export default withRouter(EditingPost)

我的错误是:

TypeError: Cannot read property 'title' of undefined
EditingPost
src/pages/Admin/Label/EditingPost.js:9
   6 |   const post = props.posts[index]
   7 |   return(
   8 |     <div>
>  9 |       {post.title}
  10 |     </div>
  11 |   )
  12 | }

但是,当我 console.log(post) 应用程序抛出 5 个日志时,前两个是 undefined,接下来的 3 个包含我正在寻找的正确信息。我的想法是,在呈现组件的 html 之前,我需要等到信息可用。然而,当我将日志放入其他组件时,我注意到了相同的行为;多个日志,第一个或两个 未定义,其余包含所需信息,然后所有组件正确加载。

我不明白为什么我在使用这个特定组件时遇到问题。我知道我需要的信息正在通过,但出于某种原因我无法像往常一样使用它。

我用谷歌搜索了一下,尝试导入有用的库,尝试使用 promises,尝试实现我能做的一切,然后再问这里。

如有任何帮助或建议,我们将不胜感激!我希望这一切对某人有意义。

我将对您的函数进行以下更改:

const EditingPost = props => {
  const index = props.match.params.post
  const post = props.posts[index];
  const title = post ? post.title : '';
  return(
    <div>
      {title}
    </div>
  )
}