调度操作后如何侦听Redux存储中的特定属性更改

Jaz*_*zzy 55 reactjs redux redux-thunk

我目前正在尝试概念化如何处理在另一个组件中的调度之后基于数据更改在组件中调度操作.

采取这种情况:

dispatch(someAjax) - >状态更新中的属性.

在此之后,我需要另一个依赖于此相同属性的组件来知道已更新并根据新值调度操作.

而不是使用某种类型的value.on(change...解决方案,处理这种类型的动作'级联'的首选方法是什么?

Pin*_*ice 76

你可以使用Redux mapStateToPropsconnectReact的componentDidUpdate(prevProps, prevState, snapshot)钩子.

所以基本上你的代码看起来像这样:

const mapStateToProps = (state) => ({ 
   specificProperty: state.specificProperty,
   // any props you need else
});

class YourComponent extends React.Component {
    render() {
      // render your component  
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        if (prevProps.specificProperty !== this.props.specificProperty) {
            // Do whatever you want
        }
    }
}

YourComponent = connect(mapStateToProps)(YourComponent);
Run Code Online (Sandbox Code Playgroud)

  • 对此更新,`componentWillUpdate`不应再与React 16一起使用.[getDerivedStateFromProps](https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops)现在是推荐的方法. (3认同)
  • 取决于 - 如果你想要新的状态,可以是`getDerivedStateFromProps`,但是你可能希望使用`componentDidUpdate`来获得更多功能. (3认同)
  • 这种方法对我来说也很有效。为了与功能组件一起使用,我将 componentDidUpdate 更改为 `useEffect(() => { /* Do What you Want */ }, [props.specificProperty])` 并将 mapStateToProps 定义为接口并设置为我的组件 props (3认同)
  • 然后适合提供的标签 (2认同)
  • 尼斯.还有,可能错字?你是说`nextProps.specificProperty!== this.props.specificProperty`? (2认同)

mar*_*son 45

有两种基本方法:在完成操作后区分状态的中间件,或使用Redux的低级store.subscribeAPI.

Redux FAQ有一个答案可以解决这个问题.此外,我保留了与Redux相关的插件和实用程序的分类列表,其中包括一组现有的商店更改订阅库,这些实现了监听数据更改的各种方法.

  • 虽然您没有具体回答这个问题,但列表中的第一项确实适用于我的案例.redux-watch是一种简单而富有创意的方式来获得此功能.再次感谢列表,这很有帮助. (4认同)