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

我目前正在尝试概念化如何处理在另一个组件中进行分派后,基于数据更改在组件中进行分派的操作。

设想一下:

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

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

与使用某种类型的 value.on(change...解决方案相比,处理这种类型的操作“级联”的首选方法是什么?

106344 次浏览

There are two basic approaches: either a middleware that diffs the state after an action is done, or using Redux's low-level store.subscribe API.

The Redux FAQ has an answer that covers this. Also, I keep a categorized list of Redux-related addons and utilities, and that includes a group of existing store change subscription libraries that implement various approaches to listening for data changes.

You may use Redux's mapStateToProps and connect with React's componentDidUpdate(prevProps, prevState, snapshot) hook.

So basically your code could look like this:

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);