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}

       <button onClick={() => dispatch({type: 'decrement'})}>-</button>

       <button onClick={() => dispatch({type: 'increment'})}>+</button>

    </>

  );

}


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容