簡體   English   中英

如何在react-redux中使用reducer狀態的值更新組件的狀態?

[英]How to update state of a component with value from reducer state in react-redux?

我有減速器給我carReducer ,我可以在EditCar組件中用作道具:

我的carReducer是:

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

在EditCar組件中,我已將carReducer聲明為:

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

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

現在在同一個組件中,我想在組件加載之前使用此carReducer更新我的intialState cardata

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

我試着用componentWillReceiveProps但是這給了我undefined在這兩個nextProps.carReducerthis.props.carReducer

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

我是react-redux新手,所以任何幫助都非常感謝。 謝謝。

在這種情況下,無需使用componentWillRecieveProps 只需在減速機中使用carReducer替換next

方法1 - 嘗試使用componentDidMount()

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

方法2 - 您可以嘗試在構造函數本身中執行此操作

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM