第一种:
const reducer = (state, action) {
const { type, payload } = action;
switch(type) {
case 'list':
return { ...state, ...payload };
default:
return state;
}
}
//ui
<div>
<button onClick={()=>{dispach({type:'list',payload:{list:state.list.concat(1)})}}>尾部添加</button>
<button onClick={()=>{dispach({type:'list',payload:{list:[1].concat(state.list)})}}>头部添加</button>
</div>
第二种:
const reducer = (state, action) {
const { type, payload } = action;
switch(type) {
case 'push':
return { ...state, list:state.list.concat(1)};
case 'unshift':
return {...state,list:[1].concat(state.list)}
default:
return state;
}
}
//ui
dispach({type:'push'})
//dispach({type:'push',payload:{value:1}})
dispach({type:'unshift'})
看到别人很多代码使用会第一种,逻辑没有写在reducer里.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…