【问题标题】:props is not initialized in react component道具未在反应组件中初始化
【发布时间】:2015-06-09 11:45:38
【问题描述】:

我开发了一个组件。在其中,我根据传递给它的 Id 加载数据,例如;

我的项目组件代码看起来像

 ItemStore.CallItem("TenantId",this.props.MetaItemId);

我的调用页面代码看起来像

<div className="box-body table-responsive no-padding list-relations" id="configureMM">
        <Item  MetaItemId={11} />
    </div>
    <div className="box-body table-responsive no-padding list-relations" id="configureMM">
        <Item  MetaItemId={12} />
    </div>

但两次都将采用第一个 id,因为 this.props 包含第一个 MetaItemId,但理想情况下,它应该在我调用 &lt;Item MetaItemId={12} /&gt; 时重新初始化,但事实并非如此,谁能告诉我我在这里缺少什么?

【问题讨论】:

  • 你能发布&lt;Item &gt;的完整代码吗?

标签: reactjs flux


【解决方案1】:

如果nextProps.MetaItemId !== this.props.MetaItemId,则需要将ItemStore.CallItem("TenantId",this.props.MetaItemId); 放入componentWillReceiveProps,所以它应该是这样的

this.componentWillReceiveProps = function(nextProps) { 
  if (nextProps.MetaItemId !== this.props.MetaItemId){
    ItemStore.CallItem("TenantId", nextProps.MetaItemId);
  }
}

这将执行调用,但除非您在某处设置状态,否则您的组件不会更新,这取决于 ItemStore.CallItem 的作用。

【讨论】:

  • 我注意到,如果我在 render() 方法中迭代一个数组属性来过滤它,如果我使用的是 lodash 的 _.filter,则项目会显示为 undefined,但如果我使用this.props.someArray.map,它们已定义。我应该使用componentWillReceiveProps 等到从网络请求中填充道具吗?
  • 得到它的工作,看起来componentWillUpdate 是票。
猜你喜欢
  • 2020-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-21
  • 2016-05-13
  • 1970-01-01
相关资源
最近更新 更多