const addDec = (state=0,action)=>{
const {type} = action;
switch(type){
case 'ADD':
return state+1;
case 'DEC':
return state - 1;
default:
return state;
}
};
const text = (state=0,action)=>{
const {type,payLoad} = action;
switch(type){
case 'TEXT':
return Object.assign({},state,{userName:payLoad});
default:
return state;
}
}
const chatReducer2 = combineReducers({
addDec,
text
})
const {getState,subscribe,dispatch} = createStore(chatReducer2);
const Counter = ({value,onADD,onDEC})=>{
return <div>
<h1>{value.addDec}</h1>
<Button type="primary" onClick={onADD}>+</Button>
<Button type="primary" onClick={onDEC}>-</Button>
</div>
}
const TextContent =({value,onText})=>{
console.log('value',value);
return <div>
<h1>{value.text.userName}</h1>
<Button type="primary" onClick={onText}>123</Button>
</div>
}
function Content(){
return(
<div>
<Counter
value={getState()}
onADD = {()=>dispatch({type:'ADD'})}
onDEC = {()=>dispatch({type:'DEC'})}
/>
<TextContent
value={getState()}
onText={()=>dispatch({type:'TEXT',payLoad:'wangxiao'})}
/>
</div>
)
}
const render=()=>{
ReactDOM.render(
<Content/>,
document.getElementById('root')
)
}
render();
subscribe(render);
需要注意的地方:
- combineReducers传入的是一个对象。
- 上文中的value是一个对象。