如何以及何时在redux状态改变后调用react组件方法

6jygbczu  于 9个月前  发布在  React
关注(0)|答案(3)|浏览(163)

在一个单独的react组件中,用户点击一个按钮=>调用一个方法=>触发一个动作=> react fetch => reducer updates state =>组件接收新的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.


但是,这是应该做的,还是没有把足够的逻辑转移到动作创作者身上的症状?

xdnvmnnf

xdnvmnnf1#

几年后回到我自己的问题。
如果我可以使用一个函数组件,我会使用react钩子useEffect。如果逻辑可以外部化,那么也许在一个 Saga 中。

useEffect(() => {
  methodToCallIfPropChanges()
}, [watchedProp]);

字符串

8wigbo56

8wigbo562#

更详细的例子将是有用的,但根据你在这里,我想我明白你在说什么。
简短的回答:是的,这是没有将足够的逻辑转移到动作创建者的症状。理想情况下,您的组件应该是纯视图组件。在大多数情况下不需要componentWillReceiveProps-您只需渲染任何 prop 即可。这就是为什么Abramov(redux的创建者)主张使用功能组件。更多关于here的内容。
如果你需要在一个带有数据的bloc调用返回后执行其他操作,你可以在操作创建器中执行。我将使用一个使用thunks的示例:

**编辑:**我添加了一个组件的示例,该组件将对音频播放器的引用作为action的参数传递。这样,action就可以在执行DMAC步骤后进行操作。

//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做thunk的东西,或者从你的redux应用程序中与有状态库接口,我强烈建议你好好阅读redux文档。上面的thunk例子的基础来自here
祝你好运,在React + Redux中玩得开心!

enxuqcxy

enxuqcxy3#

更新可以由props或state的更改引起。当组件重新呈现时,这些方法按以下顺序调用:

  • static getDerivedStateFromProps()
  • shoulderupdate()
  • render()
  • getSnapshotBeforeUpdate()
    *componentDidUpdate()尝试使用componentDidUpdate()

React文档https://reactjs.org/docs/react-component.html#updating

相关问题