2017-10-12 60 views
0

从API中获取数据并将该数据置于Redux状态后,我使用mapStatetoProps中的帮助函数来选择和修改部分该数据并将其修改为propsReact Redux - 渲染时出错,因为期待尚未到达的道具

因此,如果没有渲染,我可以在console.log中看到所有事情都应该如此。

  1. 空道具:this.props.pageContent = {}
  2. 数据取出,并映射到道具:this.props.pageContent = { pageSection: [{something here that I don't want}, {}, {}...] }
  3. 的数据,我想它选择并传递到道具: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语句diferent选项,但误差保持不变: TypeError: Cannot read property '0' of undefined

+0

后'mapStateToProps' –

回答

1

你在这里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)

因为你不知道你的道具具有pageContent,你也不能肯定pageSection存在,因为设置道具pageContent之前undefined和您试图访问一个对象里面,然后找到元素的数组内

尝试更新的代码如下:

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>); 
     } 

     } 
+0

谢谢!它感觉有点奇怪,不得不检查该对象中的每个嵌套键,但解决方案正在工作。 –

+0

不客气......很高兴帮助 –

相关问题