njo*_*aga 7 reactjs redux redux-thunk react-redux
在单个反应组件中,用户单击按钮 => 调用方法 => 触发操作 => 异步获取 => 减速器更新状态 => 组件接收新道具。
回到触发我一直使用的操作的原始组件中:
componentWillReceiveProps(nextProps){
if(nextProps.someProp !== this.props.someProp){
//ok new prop is here
this.someMethod(nextProps.someProp);
}
}
Run Code Online (Sandbox Code Playgroud)
我是否以正确的方式解决这个问题?
它看起来有点笨拙,并且作为一种回调机制与用户操作或状态变化分离。一旦有几个这样的组件,它只会使遵循组件的逻辑流程变得更加困难,我有一个包含其中 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.
Run Code Online (Sandbox Code Playgroud)
但这是应该如何完成还是这是没有将足够的逻辑转移到动作创建者的症状?
njo*_*aga 11
几年后回到我自己的问题。
如果我可以使用功能组件,我会使用react hook useEffect。如果逻辑可以外化,那么也许可以写成一个传奇。
useEffect(() => {
methodToCallIfPropChanges()
}, [watchedProp]);
Run Code Online (Sandbox Code Playgroud)
更详细的例子会很有用,但根据你在这里的内容,我想我明白你在说什么。
简短回答:是的,这是没有将足够的逻辑转移到动作创建者的症状。理想情况下,您的组件应该是一个纯视图组件。componentWillReceiveProps在大多数情况下不需要- 你只需渲染任何道具,就是这样。这就是为什么 Abramov(redux 的创建者)主张功能组件的原因。更多关于这里。
如果您需要在异步调用返回一些数据后执行其他操作,正如您所说,您可以在操作创建器中执行此操作。我将举一个使用 thunk 的例子:
编辑:我添加了一个组件示例,该组件将音频播放器的引用作为动作的参数传递。这样,动作就可以在异步步骤之后进行操作。
//An async action creator that uses the thunk pattern.
//You could call this method from your component just like any other
//action creator.
export function getMaDatums(audioPlayer, audioContext) {
return function (dispatch) {
//make the actual call to get the data
return fetch(`http://<your stuff here>`)
.then(data => {
//call dispatch again to do stuff with the data
dispatch(gotDataAction(data));
//call dispatch some more to take further actions
dispatch(...);
//since the component passed us references to these, we can
//interact with them here, after our data has loaded! FTW!
audioPlayer.doTheThings();
audioSession.doTheOtherThings();
//plus anything else you want...
});
}
}
Run Code Online (Sandbox Code Playgroud)
如果您想了解有关使用 redux 执行异步操作的更多信息,或者就此而言,与您的 redux 应用程序中的有状态库交互,我强烈建议您仔细阅读 redux 文档。上面 thunk 示例的基础来自这里。
祝你好运,享受 React + Redux 带来的乐趣!
| 归档时间: |
|
| 查看次数: |
12971 次 |
| 最近记录: |