如何使用react-redux中reducer状态的值更新组件的状态?
我有减速,让我carReducer
,我可以在EditCar组件道具使用:如何使用react-redux中reducer状态的值更新组件的状态?
我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
但是这给了我两个nextProps.carReducer
和this.props.carReducer
undefined
。
componentWillReceiveProps(nextProps) {
if (nextProps.carReducer != this.props.carReducer) {
this.setState({ cardata: nextProps.carReducer });
}
}
我是新的react-redux
所以任何帮助,高度赞赏。谢谢。
在这种情况下,没有必要使用componentWillRecieveProps
。只是carReducer
在减速取代next
this.props.carReducer的值可以在渲染部分访问。但是在componentWillReceiveProps中没有定义。 –
在这种情况下,不需要使用componentWillRecieveProps。我已经更新了我的答案,请在您的减速器中使用carReducer替换。 –
方法1 - 尝试使用componentDidMount()
componentDidMount() {
this.setState = ({
cardata: this.props.carReducer
})
}
方法2 - 你可以尝试这样做在构造函数本身
constructor(props) {
super(props);
this.state = {
cardata: props.carReducer
}
}
从方法1中得到'cardata'' undefined'并且在第二种情况下'cardata'根本没有被改变,即它变空了。 –
从reducer获取数据需要几毫秒,所以它最初是未定义的。但是当数据来临时,它必须自我放弃。你原来的'willRecieveProps()'应该可以工作。 – iamsaksham
你可以分享你减速,行动和你的商店代码? –
来自文档:React在挂载期间不会调用componentWillReceiveProps和初始道具:https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops – aabilio
为什么不直接将props.carReader指定给cardata构造函数?无论如何,你正在做的事情并不被认为是一种好的做法,你只是有了REDX状态,为什么要将它复制到组件状态中呢? – aabilio