React — useReducer

在某些场景下,useReducer 会比 useState 更适用,例如 state 逻辑较复杂且包含多个子值,或者下一个 state 依赖于之前的 state 等。并且,使用 useReducer 还能给那些会触发深更新的组件做性能优化,因为你可以向子组件传递dispatch而不是回调函数。

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

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

详细使用如下:

function Index () {
  const [count, dispath] = useReducer((state, action) => {
    switch (action.type) {
      case 'increment':
        return state + 1;
      case 'decrement':
        return state - 1;
      default:
        return state;
    }
  }, 0);
  return (
    <div>
      <h1>{count}</h1>
      <button onClick={() => dispath({ type: 'decrement' })}>-</button>
      <button onClick={() => dispath({ type: 'increment' })}>+</button>
    </div>
  )
}

在代码中通过 type 来表示 action 类型,如果 action 上的 type 为 increment 增加 state 也就是增加 count,如果 action 上的 type 为 decrement 减少 state 也就是减少 count 。

注意:如果 Reducer Hook 的返回值与当前 state 相同,React 将跳过子组件的渲染及副作用的执行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值