2016-06-10 58 views
1

我正在使用react和redux,我想在反應視圖中更新我的計數器值,我能夠控制我的redux存儲庫的最新狀態,但它不反映在我的反應視圖中。反應組件不呈現來自REDX存儲區的新數據

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

+0

你的反應組件如何與redux狀態耦合?您無法直接訪問作爲反應組件中的道具的redux狀態。 – Hareesh

+1

使用react-redux綁定您的反應應用程序http://redux.js.org/docs/basics/UsageWithReact.html –

回答

4

陣營不會自動每次一些JavaScript數據的變化重新渲染視圖,即使您的視圖綁定到這些數據。

一個陣營組件只重新呈現在少數情況下:

  1. 你叫this.setState({ ... })在組件內部
  2. 父母陣營組件進行重新渲染

還有一些其他強制重新渲染的方法,但不推薦使用它們,因爲它們速度較慢並且會使您的應用程序變得緩慢。

要更正您的示例,請在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> 
    ); 
    } 
} 

你這個玩了一會兒後,並得到熟悉終極版和如何反應的工作,我建議你看看這個庫:

這會以比您可以通過更簡潔的方式處理React和Redux之間的橋樑你自己做所有的綁定。