【问题标题】:React Native Redux getState() always 0React Native Redux getState() 总是 0
【发布时间】:2016-05-04 12:13:11
【问题描述】:

我一直在关注一些 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>
    );
  }
}

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

【问题讨论】:

    标签: reactjs react-native redux react-redux


    【解决方案1】:

    因为你的 Home 组件的 props 和 state 没有改变,它没有重新渲染,这就是你在 render 方法中看不到 Redux 存储状态更新的原因。

    使用 React 实现 Redux 的更常见方法是使用 react-redux 将容器组件连接到 Redux 状态的特定部分作为 props,这样组件将始终正确重新渲染,因为它的 props 会随着 Redux 状态而变化变化。

    【讨论】:

      猜你喜欢
      • 2018-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 2021-12-16
      相关资源
      最近更新 更多