React Redux - 渲染错误,因为期待尚未到达的道具

React Redux - Error on render because expecting props that didn't arrive yet

从 API 获取数据并将该数据放入 Redux 状态后,我在 mapStatetoProps 到 select 中使用辅助函数并修改其中的一部分数据并将其修改为 props.

因此,如果没有渲染,我可以在 console.log 中看到一切正常。

  1. 空道具:this.props.pageContent = {}
  2. 数据获取并映射到道具:this.props.pageContent = { pageSection: [{something here that I don't want}, {}, {}...] }
  3. 我想要的数据 selected 并传递给道具:this.props.pageContent = { pageSection: [{card: 'my Data'}, {}, {}...] }

但是当我将一些 props 传递给一个组件时它会抛出一个错误,因为我试图传递的那些 props 还没有到达 this.props (在这个案例 card.cardTitle)

到目前为止,这是我的代码:

class Page extends Component {
  componentWillMount() {
    this.props.fetchPageContent();
  }
  render() {
    console.log(this.props.pageContent)
        if (!this.props.pageContent.pageSection[0].card) return null;
    return (
      <div>
        <PageSection
          introSectionCardTitle={ this.props.pageContent.pageSection[0].card.cardTitle}
          introSectionCardContent={ this.props.pageContent.pageSection[0].card.cardContent}
        />
      </div>
    );
  }

有什么想法吗? 在 return 之前,我尝试使用不同选项的 if 语句,但错误保持不变: TypeError: Cannot read property '0' of undefined

你这里有问题if (!this.props.pageContent.pageSection[0].card)

替换

if (!this.props.pageContent.pageSection[0].card)

if(this.props.pageContent && this.props.pageContent.pageSection && this.props.pageContent.pageSection[0].card)

因为你不确定你的props是否有pageContent,你也不确定pageSection是否存在,因为在设置props之前pageContentundefined并且您正在尝试访问其中的一个对象,然后在数组中找到元素

尝试下面更新的代码:

class Page extends Component {
      componentWillMount() {
        this.props.fetchPageContent();
      }
      render() {
        console.log(this.props.pageContent)
        if(this.props.pageContent && this.props.pageContent.pageSection && this.props.pageContent.pageSection[0].card)
        {
            return (
              <div>
                <PageSection
                  introSectionCardTitle={ this.props.pageContent.pageSection[0].card.cardTitle}
                  introSectionCardContent={ this.props.pageContent.pageSection[0].card.cardContent}
                />
              </div>
            );
        }
        else
        {
            return (<div></div>);
        }

      }