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

后端 未结 2 1840
春和景丽
春和景丽 2021-01-30 04:57

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 scenari

相关标签:
2条回答
  • 2021-01-30 05:27

    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.

    0 讨论(0)
  • 2021-01-30 05:35

    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);
    
    0 讨论(0)
提交回复
热议问题