mapStateToProps 在 componentDidMount 中的 dispatch 之前被触发,导致数据未定义

mapStateToProps is fired before the dispatch within componentDidMount, causing data to be undefined

我正在尝试让 url 参数确定加载哪个 'article'。

但是 mapStateToProps 先触发,导致文章数据未定义。因此,在 componentDidMount 可以触发之前会抛出一条错误消息(假设将文章数据加载到状态中)。我试过把 dispatch 放在其他地方(比如在 render 中或者在它自己的方法中),仍然是同样的问题。

这是我的 comonentDidMount:

componentDidMount(){
     const params = this.props.location.search.split('/');
     this.props.dispatch(getArticleStats({articleId:params[4]}));
     

这是我的 mapStateToProps:

    const mapStateToProps=(state)=>{
    return {
        user:    state.user,
        article: state.article
    }
}

我收到的错误显示 state.article 中的数据未定义,因为派遣尚未触发:

TypeError: Cannot read property 'articleTitle' of undefined

任何智慧或指导将不胜感激。

无法在 dispatch 调用后触发 mapStateToPropsmapStateToPropsconnect 的参数,后者是高阶组件 (HOC)。这实质上使您的组件成为 connect 函数的子组件。

您的问题的解决方案很可能不是重新排序 dispatch 的调用,而是处理 article 仍未定义的情况。一个简单的虚假检查很可能会完成这项工作:if (this.props.article) ...

“组件首次挂载时数据未定义”在 React 中是一个很常见的问题。

在尝试渲染涉及异步数据的任何内容之前,尝试在您的渲染方法中添加保护措施:

render() {
  return (
    {this.state.article &&
      <h1>{this.state.article.articleTitle}</h1>
      <div>{this.state.article.articleBody}</div>
    }
  )
}