![](/img/trans.png)
[英]React-redux component update state attributes after async saga calls from 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.carReducer
和this.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.