React 新版官方文档 (一) useReducer 用法详解

本文详细介绍了React的useReducer Hook,包括其基本用法、如何在dispatch后获取最新状态值,并提供了相关参考资料链接,帮助开发者更好地理解和运用useReducer。
摘要由CSDN通过智能技术生成

在这里插入图片描述

useReducer

useReducer 是一个可以让你向组件中添加 reducer 的 Hook

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

基本用法

const reducer = (state, action) => {
...
}
const MyComponent = () => {
    const [state, dispatch] = useReducer(reducer, {age: 42})
    const handleClick = () => {
        dispatch({type:'increase'})
    }
   ...
}

比 useState 多了一个处理函数,该函数可以根据不同的分发状态来对应的改变状态

注意:state 不可修改 不能这样写, reducer 函数应当返回一个新对象

function reducer(state, action) {
  switch (action.type) {
    case 'incremented_age': {
      // 🚩 Don't mutate an object in state like this:
      state.age = state.age + 1;
      return state;
    }
function reducer(state, action) {
  switch (action.type) {
    case 'incremented_age': {
      // ✅ Instead, return a new object
      return {
        ...state,
        age: state.age + 1
      };
    }
    

不要重新执行初始函数 第一种写法会导致每次渲染时候都调用 createInitialState 函数 造成性能浪费

function createInitialState(username) {
  // ...
}
// ❌
function TodoList({ username }) {
  const [state, dispatch] = useReducer(reducer, createInitialState(username));
  
// ✅
function TodoList({ username }) {
  const [state, dispatch] = useReducer(reducer, username, createInitialState);
  // ...

dispatch 后如何使用最新的状态值

调用 dispatch 函数不会更改运行代码中的状态 ,使用最新的状态值应该是这样写

function handleClick() {
  console.log(state.age);  // 42

  dispatch({ type: 'incremented_age' }); // Request a re-render with 43
  console.log(state.age);  // Still 42!

  setTimeout(() => {
    console.log(state.age); // Also 42!
  }, 5000);
}

const action = { type: 'incremented_age' };
dispatch(action);
const nextState = reducer(state, action);
console.log(state);     // { age: 42 }
console.log(nextState); // { age: 43 }

参考

  • https://react.dev/reference/react/useReducer
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zoe_ya

如果你成功申请,可以打赏杯奶茶

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值