How to listen for specific property changes in Redux store after an action is dispatched

痞子三分冷 提交于 2019-12-03 03:01:33

问题


I am currently trying to conceptualize how to handle dispatching an action in a component based on a data change after a dispatch in another component.

Take this scenario:

dispatch(someAjax) -> property in state updates.

After this, I need another component dependent on this same property to know that is has updated and dispatch an action based on the new value.

Rather than using some type of value.on(change... solution, what is the preferred way to handle this type of action 'cascading'?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/36557089/how-to-listen-for-specific-property-changes-in-redux-store-after-an-action-is-di

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!