【发布时间】:2021-03-17 07:19:40
【问题描述】:
我试图在我的 React Native 项目中使用 Redux 来创建一个计数器应用程序。但是后来我遇到了这个错误。它说像undefined is not an object (evaluating 'state.counter')
请看一下我的代码。
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) 函数引起的。
App.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>
);
}
}
如果您能对此问题提供解决方案或建议,我将不胜感激。谢谢。
【问题讨论】:
标签: react-native redux react-redux state-management