Javascript react redux使用redux处理多个数据
我正在尝试使用redux设置全局状态,当我尝试传递单个数据时,它会工作,但当我尝试传递多个数据时,它不会工作。下面是我的代码:Javascript react redux使用redux处理多个数据,javascript,react-native,redux,Javascript,React Native,Redux,我正在尝试使用redux设置全局状态,当我尝试传递单个数据时,它会工作,但当我尝试传递多个数据时,它不会工作。下面是我的代码: <CSButton onPress={() => { this.setState({ comment : this.state.comment, region : th
<CSButton
onPress={() => {
this.setState({
comment : this.state.comment,
region : this.state.region,
},
() => this.props.commentHandler(this.state),
this.props.regionHandler(this.state),
// I am getting correct answer when I console.log here
() => console.log(this.props.comment,'this.props.comment?'),
() => console.log(this.props.region,'this.props.region?'))}}>
<Text>Button</Text>
</CSButton>
//when I try to console.log using another button, works fine for 'this.props.comment'
<Button
title='comment'
onPress={()=> console.log(this.props.comment,'comment')}>
</Button>
//But when I try to console.log `this.props.region` it gives me undefined
<Button
title='region'
onPress={()=> console.log(this.props.region,'region')}>
</Button>
function mapStateToProps(state) {
return {
region : state.region,
comment : state.comment,
}
}
function mapDispatchToProps(dispatch) {
return {
regionHandler : (state) => dispatch({ type: 'REGION', payload: state.region}),
commentHandler : (state) => dispatch({ type: 'COMMENT', payload: state.comment}),
}
}
似乎我的代码只调用了第一个处理程序,它是this.props.commentHandler(this.state)
,而不是第二个this.props.regionHandler(this.state)
有没有办法解决这个问题?任何建议或意见都将不胜感激 此.setState(partialState,callback)
只接受一个回调函数。您将在此处向其传递两个函数:
() => this.props.commentHandler(this.state),
this.props.regionHandler(this.state),
相反,请尝试:
() => {
this.props.commentHandler(this.state)
this.props.regionHandler(this.state)
}
您已将初始状态指定给状态
state=initialState
,但从未使用过。每次触发操作时,都会向视图发送一个新对象。您必须将其设置为状态。试试这个。你必须以不变的方式做到这一点
const reducer = (state = initialState, action) => {
switch (action.type)
{
case 'COMMENT':
state = {
...state,
comment: action.payload,
}
break;
case 'REGION':
state = {
...state,
region: action.payload,
}
break;
}
return state
}
我刚刚注意到你错过了休息代码>在您的代码中。
如果您对不可变状态树有疑问。参考此免费视频系列 谢谢你的评论。是的,我考虑过这个问题并尝试过,但它给了我同样的结果。你能发布你的动作和减速器的代码吗?@IsuruAbeywardana我刚做了谢谢!哇!你说得对!非常感谢!如果你能解释一下发生了什么就好了?我想知道我做错了什么。@kirimi很高兴帮助你。我更新了答案。如果您不理解,请参阅此视频。
const reducer = (state = initialState, action) => {
switch (action.type)
{
case 'COMMENT':
state = {
...state,
comment: action.payload,
}
break;
case 'REGION':
state = {
...state,
region: action.payload,
}
break;
}
return state
}