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

时间:2016-04-11 19:02:20

标签: reactjs redux redux-thunk

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

采取这种情况:

dispatch(someAjax) - >财产状况更新。

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

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

2 个答案:

答案 0 :(得分:59)

您可以将Redux的mapStateToPropsconnect与React的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);

答案 1 :(得分:40)

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

Redux常见问题解答an answer that covers this。此外,我保留了与Redux相关的插件和实用程序的分类列表,其中包括一组existing store change subscription libraries,它们实现了监听数据更改的各种方法。