How to update component state with value from reduction state in reduction reaction?

I have a reducer that gives me carReducerwhich I can use as props in the EditCar component:

My carReducer:

export default function carReducer(state = {}, action) {
    switch (action.type) {
        case 'GET_SINGLECAR':
            return {
                ...state,
                next: action.payload
            }
            break;
    }
    return state;
}

And in the EditCar component, I declared carReduceras:

    function mapStateToProps(state) {
        return {
            carReducer: state.carReducer
        }
    }

export default connect(mapStateToProps, mapDispatchToProps)(EditCar);

Now in the same component I want to update my intialState cardatawith this carReducerbefore the component loads.

constructor(props) {
    super(props);
    this.state = {
        cardata: {}
    }
}

I tried to use componentWillReceiveProps, but it gives me undefinedboth in nextProps.carReducerand this.props.carReducer.

componentWillReceiveProps(nextProps) {
    if (nextProps.carReducer != this.props.carReducer) {
        this.setState({ cardata: nextProps.carReducer });
    }
} 

I am new to react-redux, so any help is greatly appreciated. Thank.

+4
source share
2 answers

componentWillRecieveProps. next carReducer

0

1 - componentDidMount()

componentDidMount() {
  this.setState = ({
    cardata: this.props.carReducer
  })
}

2 -

constructor(props) {
  super(props);
  this.state = {
    cardata: props.carReducer
  }
}
0

Source: https://habr.com/ru/post/1675020/


All Articles