Reactjs:在主要范围之外更改道具

Reactjs: Changing props outside the main scope

我做了一个测试,我在子组件中 React.render() 并向它传递了一个道具。应用程序结构如下所示:

<App>
  <Child />
</App>

然后在 <Child /> 中,我用另一个 React.render() 渲染 <Outside /> 组件。当我签入ChromeReactfirebug时,App结构为:

<App>
  <Child />
</App>
<Outside />

而不是:

<App>
  <Child />
    <Outside />
</App>

但是,当从 <App /> 传递 {selected : true } 状态时,它在 <Outside /> 中作为道具显示得很好,但是当我将状态更改为 { selected : false } <App /><Child /><Outside /> 都没有收到更新的道具。我认为发生这种情况是因为 <Outside /> 超出了 <App /> 范围,因此数据流不畅。 (对不起我的英语)

您可以在此处查看测试:http://jsbin.com/yazaqo/1/edit?js,console,output

我想问的是:有没有其他方法可以更新 应用范围之外的组件?

Child 组件正在接收更新的 prop,只是没有记录到控制台。

只有 rendercomponentWillReceiveProps 当一个组件接收到新的道具时被调用,所以如果你将 console.log 移动到这些方法中的任何一个,你会看到更新的值.

这也是为什么 Outside 没有收到更新的道具。您在 componentDidMount 中呈现它,它只在安装组件时调用一次。

它应该在 Childrender 方法中呈现,与 ChildApp 组件中呈现的方式相同。另一种选择是在 componentWillReceiveProps 中呈现它,尽管这样做可能 运行 会遇到一些问题。

希望这对您有所帮助。