useReducer

useState 的替代方案。它接收一个形如 (state, action) => newState 的 reducer,并返回当前的 state 以及与其配套的 dispatch 方法。

在某些场景下,useReducer 会比 useState 更适用,例如 state 逻辑较复杂且包含多个子值,或者下一个 state 依赖于之前的 state 等。并且,使用 useReducer 还能给那些会触发深更新的组件做性能优化

指定初始 state:将初始 state 作为第二个参数传入 useReducer 是最简单的方法

惰性初始化state:需要将 init 函数作为 useReducer 的第三个参数传入,这样初始 state 将被设置为 init(initialArg)。可以将用于计算 state 的逻辑提取到 reducer 外部,这也为将来对重置 state 的 action 做处理提供了便利

跳过 dispatch:如果 Reducer Hook 的返回值与当前 state 相同,React 将跳过子组件的渲染及副作用的执行。(React 使用 Object.is 比较算法 来比较 state。)


const initialState = {count: 0};

function reducer(state, action) {

  switch (action.type) {

    case 'increment':

      return {count: state.count + 1};

    case 'decrement':

      return {count: state.count - 1};

    default:

      throw new Error();

  }

}

function Counter() {

  const [state, dispatch] = useReducer(reducer, initialState);

  return (

    <>

      Count: {state.count}

       

       

   

  );

}


你可能感兴趣的:(useReducer)