【问题标题】:React Native & Redux : undefined is not an object (evaluating 'state.counter')React Native 和 Redux:未定义不是对象(评估“state.counter”)
【发布时间】: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


    【解决方案1】:

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

    const initialState = {
      counter: 0,
    };
    
    const reducer = (state = initialState, action) => {
      switch (action.type) {
        ...
      }
    }
    

    【讨论】:

    • 无论如何,如果我在功能组件中编写我的 React Native 代码会怎样?你知道在功能组件中实现 redux 吗?
    • 是的,没有必要将你的组件包装在connect中,只需使用useSelectoruseDispatch钩子即可。
    • 看看this doc。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    相关资源
    最近更新 更多