> 格式:`const [state,setState] = useReducer(reducer,initState)`,useState的增强版,修改操作类似于redux
```js
const initState = [
{ id:1, name: "goods1", price: 98, qty: 2 },
{ id:2, name: "goods2", price: 198, qty: 2 },
{ id:3, name: "goods3", price: 998, qty: 1 },
];
const reducer = (state, action) => {
switch (action.type) {
case 'add':
return [action.goods, ...state];
case 'remove':
return state.filter(item => item.id != action.id);
case 'change':
return state.map(item=>{
if(item.id === action.id){
item.qty = action.qty;
}
return item;
})
case 'clear':
return []
default:
throw new Error('type error');
}
}
const MyHook = () => {
const [state, dispatch] = useReducer(reducer, initState);
return <div>
<ul>
{
state.map(item=><li key={item.name}>{item.name}-{item.price}</li>)
}
</ul>
<button onClick={()=>{
dispatch({type:'add',goods:{name:'newGoods',price:111,qty:1}})
}}>添加商品</button>
</div>
}
```
> PS: 如果 Reducer Hook 的返回值与当前 state 相同,React 将跳过子组件的渲染及副作用的执行
这是一条小尾巴ヾ(o◕∀◕)ノヾ~
须知少日拏云志,曾许人间第一流!
浙公网安备 33010602011771号