[React] Use the useReducer Hook and Dispatch Actions to Update State (useReducer, useMemo, useEffect...

本文探讨了在React中使用useReducer钩子替代useState的方法,通过集中管理分散在Web应用中的逻辑,实现更高效的状态更新。文章详细介绍了useReducer的用法,包括初始化状态、处理副作用及使用useEffect进行本地存储的更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

As an alternate to useState, you could also use the useReducer hook that provides state and a dispatch method for triggering actions. In this lesson, we’ll centralize logic that is spread across a web application and centralize it using the useReducer hook.

NOTE: Since hooks are still a proposal and only pre-released, it’s not currently recommended to use them in production.

useReducer:

  const [todos, dispatch] = useReducer((state, action) => {
    switch (action.type) {
      case "ADD_TODO":
        todoId.current += 1;
        return [
          ...state,
          { id: todoId.current, text: action.text, completed: false }
        ];
      case "DELETE_TODO":
        return state.filter(todo => todo.id !== action.id);
      case "TOGGLE_TODO":
        return state.map(todo =>
          todo.id === action.id ? { ...todo, completed: !todo.completed } : todo
        );
      default:
        return state;
    }
  },initialValue);

 

useReducer can accept second param as a function, so we can replace 'initialValue' with a function return a 'initialValue', which means we can using cache for the function if the param doesn't change, we always return the cache. To do that we can use 

 

useMemo:

  const [todos, dispatch] = useReducer((state, action) => {
    switch (action.type) {
      case "ADD_TODO":
        todoId.current += 1;
        return [
          ...state,
          { id: todoId.current, text: action.text, completed: false }
        ];
      case "DELETE_TODO":
        return state.filter(todo => todo.id !== action.id);
      case "TOGGLE_TODO":
        return state.map(todo =>
          todo.id === action.id ? { ...todo, completed: !todo.completed } : todo
        );
      default:
        return state;
    }
  }, useMemo(initialValue, []));

The second parameter of 'useMemo' indicates when the memorized version should change. In our case, we want it to always be the same, so passing an empty array conveys that message.

 

To handle side effect of action, in our case, is update localstorage, we can use useEffect:

useEffect(
  () => {
    window.localStorage.setItem("todos", JSON.stringify(todos));
  },
  [todos]
);

 

---

 

转载于:https://www.cnblogs.com/Answer1215/p/10426941.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值