简体   繁体   中英

Which Life cycle method should be preferred when using redux?

从 props 中的 redux store 获取数据时应该首选哪种生命周期方法?

I am not sure how exactly is your component written, but the general pattern to follow would be to connect your component to your redux store, and map the value from your store to your components props.

From there, your component will be subscribed to the data from your store, which you can access on componentDidMount lifecycle hook, and any other updates to the store can be accessed in the componentDidUpdate hook. Similarly, any changes on your props will trigger re-rendering on your component.

const mapStateToProps = (state) => ({
  data: state.data,
});

class Checkbox extends React.Component {

  componentDidMount() {
    const { data } = this.props;
  }

  componentDidUpdate(prevProps, prevState,) {

  }

}

export default connect(mapStateToProps)(Checkbox);

Generally you will not need any life cycle method but it depends on your usecase and how you want to use your data that is coming from redux store.Generally flow can be like this:

  1. Connect your component with redux store.
  2. Map your state to props and get the that you want in component.
  3. In componentDidMount(),you will get the data in props.
  4. And if you want to check if your data is changed or not from store then you can use componentDidUpdate(prevProps,prevState) method to check.

Here is a little demo:

class YourComponent extends React.Component {


  componentDidMount() {
    console.log("You will get your data here:",this.props.data);
  }

  componentDidUpdate(prevProps, prevState,) {
    //Here you can compare data if it is changed or not.
    if(prevProps.data !== this.props.data){
        console.log("Your data is changed.");   
    }
  }

}

//Map your state to props
const mapStateToProps = store =>{
    const data = store.data
    return {
        data
    }
};

//Connect your component with redux store.
export default connect(mapStoreToProps)(YourComponent);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM