react组件不会从redux store中呈现新数据

时间:2016-06-10 08:32:35

标签: javascript reactjs redux

我正在使用react和redux,我想在反应视图中更新我的计数器值,我能够控制我的redux商店的最新状态,但它没有反映在我的反应视图中。

const counter = (state = 0, action) => {
  console.log(action);
  if(action.type == "INCREMENT")
    return state + 1;
  if(action.type == "DECREMENT")
    return state - 1;
  else 
    return state; // return same state if action not identified  
}

const {createStore} = Redux;

const store = createStore(counter);

class Counter extends React.Component {
  constructor() {
    super();
  }

  render() {
    return (
      <div>
      <div>{this.props.state.getState()}</div>
      <button onClick={this.props.onIncrement} >INC</button>
      <button onClick={this.props.onDecrement} >DEC</button>
      </div>
    );
  }
}


const render = () => {
  ReactDOM.render(
    <Counter 
    state={store} 
    onIncrement={
      () => store.dispatch({ type : "INCREMENT" })
    }
    onDecrement={
      () => store.dispatch({ type : "DECREMENT" })
    }
  />,
  document.querySelector('#counter'));
}

store.subscribe(function() {
  console.log(store.getState())
});

render();

Demo

1 个答案:

答案 0 :(得分:4)

每当某些Javascript数据发生更改时,即使您的视图绑定到该数据,React也不会自动重新呈现视图。

React组件仅在少数情况下重新渲染:

  1. 您在组件
  2. 中调用this.setState({ ... })
  3. 重新呈现父React组件
  4. 还有其他一些强制重新渲染的方法,但不推荐使用它们,因为它们速度慢得多,会让你的应用变得迟钝。

    要更正样本,请对state对象上的实际数据进行数据绑定,而不是props。这样React知道在计数器改变时重新渲染你的组件。这在小样本中可能不是很重要,但是当您想要重用组件或将其嵌入更大的页面时,这一点非常重要。

    然后订阅您的商店,并在回调中调用setState进行任何更改。这样React可以决定你的重新渲染应该在什么时候发生。

    class Counter extends React.Component {
      constructor(props) {
        super();
        this.state = {counter: 0}; // Setup initial state
        this.storeUpdated = this.storeUpdated.bind(this);
        props.store.subscribe(this.storeUpdated); // Subscribe to changes in the store
      }
    
      storeUpdated() {
        this.setState( // This triggers a re-render
          {counter: this.props.store.getState()});
      }
    
      render() {
        return (
          <div>
          <div>{this.state.counter}</div>
          <button onClick={this.props.onIncrement} >INC</button>
          <button onClick={this.props.onDecrement} >DEC</button>
          </div>
        );
      }
    }
    

    在您玩了一段时间并熟悉Redux和React的工作原理之后,我建议您查看这个库:

    它以更加干净的方式处理React和Redux之间的桥梁,而不是通过自己手动完成所有绑定来实现。

相关问题