(请帮助修复我的代码(我想写计数器增量代码,以便理解redux的情况:
- 能够增加简单计数器
- 能够用物体增加计数器
- 现在,面对柜台1在主页面上保持不败
这是我的减速器,也是我创建的方式
import * as ActionTypes from "../ActionTypes";
const INITIAL_STATE = {
counter: {
counter1: 0,
counter2: 0,
counter3: {
innerCount1: 0,
innerCount2: 0,
},
},
};
export const Auth = (state = INITIAL_STATE, action) => {
const { type, payload } = action;
let a;
switch (type) {
case ActionTypes.INCREMENT1:
a = {
...state,
counter: {
counter1: counter1 + 1,
},
};
return a;
default:
return state;
}
};
export default Auth;
ActionTypes文件
export const INCREMENT1 = "INCREMENT1";
和主页
import React from "react";
import { View, Text, Button } from "react-native";
import { incrementCounter1 } from "./states/redux/ActionCreators/auth";
import { connect, useDispatch } from "react-redux";
const CounterReduxScreen = ({ counterRedux, incrementCounter1 }) => {
const dispatch = useDispatch();
const handleCounterIncrement1 = async () => {
incrementCounter1();
};
return (
<View>
<Text style={styles.text}>Redux Pratice</Text>
<Button title="Increase" onPress={handleCounterIncrement1} />
<View>
<Text>Value first counter: {counterRedux.counter1}</Text>
</View>
</View>
);
};
const mapStateToProps = (state) => {
return {
counterRedux: state.counter,
};
};
const mapDispatchToProps = (dispatch) => {
return {
incrementCounter1: () => dispatch(incrementCounter1()),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(CounterReduxScreen);
您在减速器内为case ActionTypes.INCREMENT1
设置的状态不正确。进行以下更改以修复它:
case ActionTypes.INCREMENT1:
a = {
...state,
counter: {
// ...state.counter is needed so that counter2 and counter3 values are not removed
...state.counter,
// counter1 is not directly accessible which is why you're getting the error
// you need to access it via state.counter as shown below
counter1: state.counter.counter1 + 1,
},
};
return a;
为了增加counter3
的innerCount1
的值,您可以更新状态,如下所示:
case ActionTypes.INCREMENT3A:
a = {
...state,
counter: {
...state.counter,
counter3: {
...state.counter.counter3,
innerCount1: state.counter.counter3.innerCount1 + 1,
},
},
};
return a;