我想實現用簡單的終極版計數器組成部分,創造了store
使用createStore
和使用store.dispatch
簡單終極版Counter組件實現
完整代碼:
/*==================================================
This is only to format the code, I have used this editor,
you can scroll down for the fiddle having error.
==================================================*/
const createStore = Redux.createStore;
const counter = (state = {
counter: 0
}, action) => {
console.log('counter', state)
switch (action.type) {
case 'INCREMENT':
return state.counter + 1;
case 'DECREMENT':
return state.counter - 1;
default:
return state;
}
}
const store = createStore(counter);
let Counter = React.createClass({
getInitialState() {
return store.getState()
},
incrementCounter() {
store.dispatch({
type: 'INCREMENT'
});
},
decrementCounter() {
store.dispatch({
type: 'DECREMENT'
});
},
render() {
console.log('NEW STATE:', store.getState(), this.state)
return (
<div>
<p>{this.state.counter}</p>
<div>
<button onClick={this.incrementCounter}>+</button>
<button onClick={this.decrementCounter}>-</button>
</div>
</div>
)
}
})
ReactDOM.render(< Counter/> , document.getElementById('container'))
我的問題:我是不是能夠得到在渲染塊更新儲值當我點擊incrementCounter
和decrementCounter
功能
注:請與我裸露,我是新來的終極版。
作爲亞歷山大已經在這裏做,你也減速需要使用Object.assign因爲它是返回一個整數(新計數)而不是定義爲初始狀態的狀態對象,例如{counter:1}。 –
@ alexander-t,感謝您的幫助。我真的很感激你是否也可以給我一個'Provider'的例子。請........ –
@RAVI MONE看看我的更新... –