首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >子组件的道具在父组件以空开始时不会更新

子组件的道具在父组件以空开始时不会更新
EN

Stack Overflow用户
提问于 2017-07-15 12:45:51
回答 1查看 73关注 0票数 0
代码语言:javascript
运行
复制
// 1 - Parent - Wrong
render() {
const { record } = this.state;
if (!record) { return null; }
return (
  <div>
    <p>Now this is visible</p>
    <Children id={record.id};
  </div>
  );
}

// 2 - Parent - Right
render() {
  const { record } = this.state;
  const recordId = record ? record.id : null;

  return (
    <div>
      <p>Now this is visible</p>
      <Children id={recordId};
    </div>
  );
}

// Children
componentWillReceiveProps(nextProps) {
  console.log(nextProps.id);
}

如果状态变为: this.state ={ record:{ id:'demo‘}}

编写第一种方法的代码时,即使父记录由于接收到了新的状态而变得可见,nextProps在子componentWillReceiveProps中也始终是未定义的。

而第二种则是正常工作的。

为什么第一种方法不正确?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-15 15:33:43

根据正式文件,React在安装过程中不使用初始道具调用componentWillReceiveProps。只有当组件的某些道具可能更新时,它才会调用此方法。

我为您的问题找到了解决办法,并为解决方案创建了下面的小提琴。它应该能解决你所有的问题。

小提琴- https://jsfiddle.net/4o7o6cmw/4/

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45118353

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档