【发布时间】:2016-11-28 20:51:02
【问题描述】:
在单个反应组件中,用户单击按钮 => 调用方法 => 触发操作 => 异步获取 => 减速器更新状态 => 组件接收新道具。
回到触发我一直在使用的操作的原始组件:
componentWillReceiveProps(nextProps){
if(nextProps.someProp !== this.props.someProp){
//ok new prop is here
this.someMethod(nextProps.someProp);
}
}
我是否以正确的方式处理这件事?
它只是看起来有点笨拙,并且作为一种与用户操作或状态变化无关的回调机制。一旦有其中一些,它只会使遵循组件的逻辑流程变得更加困难,我有一个包含其中 3 个的组件,并且已经认为这并不容易推理,尤其是当它们是相关流程的一部分时 a > b > C 。我最终得到了这种东西:
componentWillReceiveProps(nextProps){
if(this.patchJavaScriptWillLoad(nextProps)){
this.createPatchInstance();
// method fires an action which will also result in state change that triggers the below.
}
if(this.patchInstanceWillBeReady(nextProps)){
this.startPatchAudio(nextProps.webAudioPatch.instance);
// method fires an action which will also result in state change that triggers the below.
}
if(this.patchParametersWillChange(nextProps)){
this.updateWebAudioPatchParameters(nextProps.webAudioPatchParameters);
}
}
// abstracted away if conditions to make componentWillReceiveProps more readable.
但这是应该如何完成的,还是没有将足够的逻辑传递给动作创建者的症状?
【问题讨论】:
-
不知道你的函数的细节很难判断,但感觉你的回调逻辑可以转移到动作创建者,特别是如果你使用 redux-thunk。
-
componentWillReceiveProps 正在被弃用。查找 getDerivedStateFromProps
标签: reactjs redux react-redux redux-thunk