react-native - React Native & Redux:未定义不是一个对象(评估'state.counter')
问题描述
我试图在我的 React Native 项目中使用 Redux 来创建一个计数器应用程序。但是后来我遇到了这个错误。它说像 undefined is not an object (evaluating 'state.counter')
请看一下我的代码。
计数器.js
class Counter extends Component {
state = {counter: 0};
render() {
return (
<View style={styles.container}>
<View style={styles.counterPart}>
<TouchableOpacity onPress={() => this.props.increaseCounter()}>
<Text style={styles.text}>Increase</Text>
</TouchableOpacity>
<Text style={styles.text}>{this.props.counter}</Text>
<TouchableOpacity onPress={() => this.props.decreaseCounter()}>
<Text style={styles.text}>Decrease</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
function mapStateToProps(state) {
return {
counter: state.counter,
};
}
function mapDispatchToProps(dispatch) {
return {
increaseCounter: () => dispatch({type: 'INCREASE_COUNTER'}),
decreaseCounter: () => dispatch({type: 'DECREASE_COUNTER'}),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Counter);
该错误似乎是由mapStateToProps(state)
上述功能引起的。
应用程序.js
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREASE_COUNTER':
console.log('Enter INCREASE_COUNTER reducer');
return {counter: state.counter + 1};
case 'DECREASE_COUNTER':
console.log('Enter DECREASE_COUNTER reducer');
return {counter: state.counter - 1};
}
return state;
};
const store = createStore(reducer);
const initialState = {
counter: 0,
};
class App extends Component {
render() {
return (
<Provider store={store}>
<Counter />
</Provider>
);
}
}
如果您能对此问题提供解决方案或建议,我将不胜感激。谢谢你。
解决方案
我认为问题在于您无法initialState
在减速器中访问,请尝试将声明移动到顶部reducer
。
const initialState = {
counter: 0,
};
const reducer = (state = initialState, action) => {
switch (action.type) {
...
}
}
推荐阅读
- javascript - loop over js array in d3 callback tree
- python-3.x - 如何使 kivymd 中的滑动实现选项卡的内容
- java - BorderLayout.PAGE_START / NORTH 中的滚动条
- jsf - 如何将 DeltaSpike @WindowScoped bean 移植到 JSF 2.2+?
- dataweave - Dataweave:根据分数创建排名
- java - vulkan bdridge 在 Android 上的 C++ OpenCL 和 Java GLES 之间
- swift - 为什么我会收到此警告以在符合默认实现的协议的类型上实现“hash(into:)”
- ios - Visual Studio Mac App 发布(来自存档)错误:参数名称“key”不能为空
- loops - 如何在火花中创建循环?
- javascript - Vue路由器没有路由