zoukankan      html  css  js  c++  java
  • [React] Use the useReducer Hook and Dispatch Actions to Update State (useReducer, useMemo, useEffect)

    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]
    );

    ---

  • 相关阅读:
    NDK开发之ndk-build命令详解
    NDK开发之Application.mk文件详解
    Unity3D自己常用代码
    投资股权众筹项目,至少需要关注6个方面
    2015,我的投资理财策略(股权众筹+P2P网贷+活期理财)
    2015,我的投资理财策略(股权众筹+P2P网贷+活期理财)
    关于weight属性使用的一些细节
    xtu summer individual 5 F
    BNUOJ 1268 PIGS
    BNUOJ 2105 Distance Queries
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10426941.html
Copyright © 2011-2022 走看看