Reactjs 反应本机Redux getState()始终为0

Reactjs 反应本机Redux getState()始终为0,reactjs,react-native,redux,react-redux,Reactjs,React Native,Redux,React Redux,我一直在学习React Redux教程,因此决定尝试并实现以下示例之一: import {createStore} from 'redux'; export default class Home extends Component { constructor(props) { super(props); this.store = createStore(this.counter); } counter(state = 0, action) { switch

我一直在学习React Redux教程,因此决定尝试并实现以下示例之一:

import {createStore} from 'redux';

export default class Home extends Component {
  constructor(props) {
    super(props);
    this.store = createStore(this.counter);
  }

  counter(state = 0, action) {
    switch(action.type) {
      case 'INCREMENT':
        return state + 1;
      break;
      case 'DECREMENT':
        return state - 1;
      break;
      default:
        return state;
      break
    }
  }

  increment() {
    this.store.dispatch({type: 'INCREMENT'});
  }

  render() {
    return (
      <View>
        <Text>{this.store.getState()}</Text>
        <TouchableOpacity onPress={() => this.increment()}>
          <Text>INCREMENT</Text>
        </TouchableOpacity>
      </View>
    );
  }
}
从'redux'导入{createStore};
导出默认类Home extends组件{
建造师(道具){
超级(道具);
this.store=createStore(this.counter);
}
计数器(状态=0,动作){
开关(动作类型){
案例“增量”:
返回状态+1;
打破
“减量”一案:
返回状态-1;
打破
违约:
返回状态;
打破
}
}
增量(){
this.store.dispatch({type:'INCREMENT'});
}
render(){
返回(
{this.store.getState()}
this.increment()}>
增量
);
}
}

如果我
console.log
state的值在
计数器中,我可以看到它在变化。但是,当我在
render
方法中执行
this.store.getState()
时,它保持在0

,因为您的主组件的道具和状态没有改变,它没有重新渲染,这就是为什么您在render方法中没有看到Redux存储的状态更新

使用React实现Redux的一种更常见的方法是将容器组件作为道具连接到Redux状态的特定部分,这样组件将始终正确地重新渲染,因为其道具会随着Redux状态的更改而更改