在 state/props 更改时调用操作创建者

calling action creators on state/props change

父组件:

{this.state.Child2 ? (
  <Child2 Colorvalue={this.state.activeColor} somename={this.state.name} />
) : (
  <Child1 somename={this.state.name} Colorvalue={this.state.activeColor} />
)}

在 child1 和 child2 组件中,我添加了对 actioncreator 的调用(api 调用)以获取一些信息 - 在 ComponentWillMount 方法中 - 一切正常..

this.props.fetchData(somename, Colorvalue);

现在,如果父项的颜色值发生变化,我需要更新两个子项。我应该使用新的 'Colorvalue' 调用 actioncreator 我应该在两个子组件的 update/receive props 方法中再调用一次吗?如何处理这种情况?

在每个子组件中,如果我这样做,将有 2 次调用 actionCreators?

您可以在 parent 中 dipatch API 调用 this.props.fetchData(...)。然后在 parent 中更新 this.state.activeColor。现在将该值作为道具传递给 Child1Child2.

在您的 child 组件中,由于您在 ComponentWillMount 中调度操作,不会 发生新的 API当您从 parent.

提供新道具时调用它们

如果你想在收到新道具时更新 child 组件的内部状态(如果有的话),你可以使用 componentWillReceiveProps(nextProps).


更新:

Child1Child2 通过道具从 parent 接收新颜色。 因此,如果你想在接收新道具时触发 API 调用,请在 child 个组件的 componentWillReceiveProps 内调度 this.props.fetchData(...)

希望你使用的是 ES6 类:

componentWillReceiveProps(nextProps) {
    if (this.props.Colorvalue !== nextProps.Colorvalue) {
        this.props.fetchData(this.props.somename, nextProps.Colorvalue);
    }
}

我还假设您已使用 connect.

将动作创建器 fetchData 作为道具映射到您的 child 组件