在单个 React 组件中,用户单击按钮 => 调用方法 => 触发操作 => 异步获取 => 减速器更新状态 => 组件接收新的 props。
回到触发我一直在使用的操作的原始组件:
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.
但这是否应该这样做,或者这是没有将足够的逻辑转移给动作创建者的症状吗?
多年后回到我自己的问题。
如果我可以使用功能组件,我会使用react hook useEffect。如果逻辑可以外化,那么也许可以写成一个传奇。
useEffect(() => {
methodToCallIfPropChanges()
}, [watchedProp]);
更详细的示例会很有用,但是根据您这里的内容,我想我明白您的意思。
简短回答:是的,这是没有向动作创建者传递足够逻辑的症状。理想情况下,您的组件应该是纯视图组件。在大多数情况下不需要
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...
});
}
}
如果您想了解更多有关使用 redux 进行异步操作的信息,或者想了解有关与 redux 应用程序中的有状态库交互的更多信息,我强烈建议您仔细阅读 redux 文档。上面的 thunk 示例的基础来自here。
祝你好运,享受 React + Redux 的乐趣!
更新可能是由 props 或 state 的更改引起的。当组件重新渲染时,这些方法将按以下顺序调用:
React 文档https://reactjs.org/docs/react-component.html#updating