javascript - 如何在反应原生的一个redux中添加多个计数器
问题描述
我想添加多个计数器,例如 countA、countV、countR,并希望在 onPress 上更新特定计数器。但是当我更新其中任何一个时。然后所有计数器更新。
这是我在 App.js 中尝试过的
const initialState={
countA:0,
countV:0,
countR:0,
};
function reducer(state = initialState, action){
switch(action.type){
case "INCREMENTA":
return {
countA: state.countA + 1,
}
case "INCREMENTV":
return {
countV: state.countV + 1,
}
case "INCREMENTR":
return {
countR: state.countR+ 1,
}
default:
return state;
}
}
const store = createStore(reducer);
在 screen.js 中
incrementA = () => {
this.props.dispatch({type:"INCREMENTA"})
}
incrementV = () => {
this.props.dispatch({type:"INCREMENTV"})
}
incrementR = () => {
this.props.dispatch({type:"INCREMENTR"})
}
///here is onPress button
const mapStateToProps=(state)=>({
countA:state.countA,
countV:state.countV,
countR:state.countR
})
export default connect(mapStateToProps)(detailScreen);
请忽略它 = 我想添加多个计数器,如 countA、countV、countR 并想更新 onPress 上的特定计数器。但是当我更新其中任何一个时。然后所有计数器更新。我想添加多个计数器,例如 countA、countV、countR,并希望在 onPress 上更新特定计数器。但是当我更新其中任何一个时。然后所有计数器更新。
解决方案
在 Redux reducer 中,你必须返回全新的状态,所以你的代码应该是:
const initialState={
countA:0,
countV:0,
countR:0,
};
function reducer(state = initialState, action){
switch(action.type){
case "INCREMENTA":
return {
...state,
countA: state.countA + 1,
}
case "INCREMENTV":
return {
...state,
countV: state.countV + 1,
}
case "INCREMENTR":
return {
...state,
countR: state.countR+ 1,
}
default:
return state;
}
}
const store = createStore(reducer);
推荐阅读
- visual-studio-code - 如何在 Visual Studio Code 的 Rust 项目中查看外部库的源代码?
- python - MongoEngine 递归嵌入
- android - 尝试使用 p4a 编译“Hello World”Kivy 项目
- django - 如何在 django 中展望并订购查询集?
- json - IdentityServer 4:我必须加密对 api 的 json 调用吗?
- java - 生成长固定大小的随机字符串
- javascript - 有没有办法制造某些组件(即s) 在网页上自动滚动?
- python - 如何使用css从单个href中的多个url中选择单个url?
- .htaccess - .htaccess 带有查询参数的永久重定向
- python - 为什么 fork() 系统调用在 windows 的 python 中的替代品?