[英]How to update state of a component with value from reducer state in react-redux?
I have reducer that gives me carReducer
, which I can use as props in EditCar Component: 我有减速器给我carReducer
,我可以在EditCar组件中用作道具:
My carReducer
is: 我的carReducer
是:
export default function carReducer(state = {}, action) {
switch (action.type) {
case 'GET_SINGLECAR':
return {
...state,
next: action.payload
}
break;
}
return state;
}
And in EditCar Component I have declared carReducer
as: 在EditCar组件中,我已将carReducer
声明为:
function mapStateToProps(state) {
return {
carReducer: state.carReducer
}
}
export default connect(mapStateToProps, mapDispatchToProps)(EditCar);
Now in the same component I want to update my intialState cardata
with this carReducer
before the component loads. 现在在同一个组件中,我想在组件加载之前使用此carReducer
更新我的intialState cardata
。
constructor(props) {
super(props);
this.state = {
cardata: {}
}
}
I tried using componentWillReceiveProps
but this gives me undefined
in both nextProps.carReducer
and this.props.carReducer
. 我试着用componentWillReceiveProps
但是这给了我undefined
在这两个nextProps.carReducer
和this.props.carReducer
。
componentWillReceiveProps(nextProps) {
if (nextProps.carReducer != this.props.carReducer) {
this.setState({ cardata: nextProps.carReducer });
}
}
I am new in react-redux
so any help is highly appreciated. 我是react-redux
新手,所以任何帮助都非常感谢。 Thank you. 谢谢。
There is no need to use componentWillRecieveProps
in this case. 在这种情况下,无需使用componentWillRecieveProps
。 Just replace next
with carReducer
in your reducer 只需在减速机中使用carReducer
替换next
Method 1 - Try to use componentDidMount()
方法1 - 尝试使用componentDidMount()
componentDidMount() {
this.setState = ({
cardata: this.props.carReducer
})
}
Method 2 - You can try to do it in the constructor itself 方法2 - 您可以尝试在构造函数本身中执行此操作
constructor(props) {
super(props);
this.state = {
cardata: props.carReducer
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.