Ant Design Pro V5精讲(基础篇六):useReducer

535 阅读1分钟

需求场景

1.有一些state本身有很多子值,例如一个对象,这时候用useState有点麻烦,因为用户更多关注的颗度是这个对象,而不是对象中的某一个属性上,整个state(含子值多个)对外是一个整体。

2.有一些state本身需要依赖之前的state进行逻辑上计算。

3.大型组件树时,父组件向子组件传递dipatch,改变父子组件传递回调函数的传统用法,我们可以让useReducer与useContext配合使用,完成dispatch函数的作为传值对象,从而实现了简化的redux的功能,即局部单向数据流。

语法

const [state, dispatch] = useReducer(reducer, initialArg, init); useReducer传入一个reducer函数后根据action更新state,最后返回新的state值及配套dipatch函数。

小结:useState 的替代方案(适合管理多个子值的state对象)。它接收一个形如 (state, action) => newState 的 reducer,并返回当前的 state 以及与其配套的 dispatch 方法。(如果你熟悉 Redux 的话,就已经知道它如何工作了。)

特性

  • 返回一个state和一个dispatch
  • 第三个参数传入支持, init(initialArg)把初始化state的逻辑可以放在reducer外部。

用法说明

const initialState={num:0};

const reducer=(state,action)=>{ switch(action.type)

               {
                   case 'decre':

                       return {...state,num:state.num-1}

                    default: return state;

               }    

}

const ComponentReducer=()=>{ const [state,dispatch]=useReducer(reducer,initialState)

  const {num}=state;

   return <button onClick={()=>dispatch({type:'decre'})})</button>

}

小结:

另外可以把useContext与useReducer结合起来用,实现简化的Redux进行状态管理,因为useContext可以实现状态的在各个组件中的共享。