簡體   English   中英

react組件未從redux存儲中呈現新數據

[英]react component not render new data from redux store

我正在使用React和Redux,我想在React視圖中更新我的計數器值,我能夠管理Redux存儲的最新狀態,但它不能反映在我的React視圖中。

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();

演示版

每當某些Javascript數據更改時,即使視圖綁定到該數據,React也不會自動重新呈現該視圖。

React組件僅在以下幾種情況下重新渲染:

  1. 您可以在組件內部調用this.setState({ ... })
  2. 父React組件被重新渲染

還有其他幾種強制重新渲染的方法,但不建議使用它們,因為它們速度慢得多,會使您的應用程序運行緩慢。

要更正示例,請對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之間的橋梁。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM