首页 > 解决方案 > 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>
    );
  }
}

如果您能对此问题提供解决方案或建议,我将不胜感激。谢谢你。

标签: react-nativereduxreact-reduxstate-management

解决方案


我认为问题在于您无法initialState在减速器中访问,请尝试将声明移动到顶部reducer

const initialState = {
  counter: 0,
};

const reducer = (state = initialState, action) => {
  switch (action.type) {
    ...
  }
}

推荐阅读