React Native 和 Redux:undefined 不是一个对象(评估 'state.counter')

React Native & Redux : undefined is not an object (evaluating 'state.counter')

我试图在我的 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>
    );
  }
}

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

我认为问题是你无法在 reducer 中访问 initialState,尝试像这样将声明移动到 reducer 的顶部。

const initialState = {
  counter: 0,
};

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

我想你的问题可以通过在switch中添加default situation来解决。

 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};
     default:        // <--- HERE
       return state; // <--- HERE
   }
 };