如何操纵上下文 - 将函数附加到上下文或将调度包装在钩子中?

How to manipulate context - attach function to context or wrap dispatch in hook?

我想知道推荐的操作和公开新 React 上下文的最佳实践是什么。

操作上下文状态的最简单方法似乎是将一个函数附加到上下文,该函数可以调度 (usereducer) 或设置状态 (useState) 以在调用后更改其内部值。

export const TodosProvider: React.FC<any> = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, null, init);

  return (
    <Context.Provider
      value={{
        todos: state.todos,
        fetchTodos: async id => {
          const todos = await getTodos(id);
          console.log(id);
          dispatch({ type: "SET_TODOS", payload: todos });
        }
      }}
    >
      {children}
    </Context.Provider>
  );
};

export const Todos = id => {
  const { todos, fetchTodos } = useContext(Context);
  useEffect(() => {
    if (fetchTodos) fetchTodos(id);
  }, [fetchTodos]);
  return (
    <div>
      <pre>{JSON.stringify(todos)}</pre>
    </div>
  );
};

然而,我被告知直接公开和使用反应上下文对象可能不是一个好主意,而是被告知将其包装在钩子中。

export const TodosProvider: React.FC<any> = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, null, init);

  return (
    <Context.Provider
      value={{
        dispatch,
        state
      }}
    >
      {children}
    </Context.Provider>
  );
};

const useTodos = () => {
  const { state, dispatch } = useContext(Context);
  const [actionCreators, setActionCreators] = useState(null);

  useEffect(() => {
    setActionCreators({
      fetchTodos: async id => {
        const todos = await getTodos(id);
        console.log(id);
        dispatch({ type: "SET_TODOS", payload: todos });
      }
    });
  }, []);

  return {
    ...state,
    ...actionCreators
  };
};

export const Todos = ({ id }) => {
  const { todos, fetchTodos } = useTodos();
  useEffect(() => {
    if (fetchTodos && id) fetchTodos(id);
  }, [fetchTodos]);

  return (
    <div>
      <pre>{JSON.stringify(todos)}</pre>
    </div>
  );
};

我在此处为两种变体制作了 运行 代码示例:https://codesandbox.io/s/mzxrjz0v78?fontsize=14

所以现在我有点困惑,不知道这两种方法中哪一种是正确的方法?

我认为没有官方答案,所以让我们在这里尝试使用一些常识。我觉得直接用useContext就可以了,不知道是谁告诉你不要用的,也许HE/SHE应该指点官方文档。如果不应该使用它,React 团队为什么要创建该钩子? :)

不过,我可以理解,尽量避免在 Context.Provider 中创建一个巨大的对象,如 value,一个将状态与操作它的函数混合在一起的对象,可能像你的例子一样具有异步效果.

但是,在您的重构中,您为动作创建者引入了一个非常奇怪且绝对不必要的 useState,您只是在第一种方法中内联定义了它。在我看来,您正在寻找 useCallback 。那么,你为什么不这样混合两者呢?

  const useTodos = () => {
    const { state, dispatch } = useContext(Context);
    const fetchTodos = useCallback(async id => {
      const todos = await getTodos(id)
      dispatch({ type: 'SAVE_TODOS', payload: todos })
    }, [dispatch])

    return {
      ...state,
      fetchTodos
    };
}

您的调用代码不需要那种奇怪的检查来验证 fetchTodos 确实存在。

export const Todos = id => {
  const { todos, fetchTodos } = useContext(Context);
  useEffect(() => {
    fetchTodos()
  }, []);

  return (
    <div>
      <pre>{JSON.stringify(todos)}</pre>
    </div>
  );
};

最后,除非你真的需要使用这个 todos + fetchTodos 组合来自 Todos 树下的更多组件,你没有在你的问题中明确说明,我认为在不需要时使用 Context 会使事情复杂化。删除额外的间接层并直接在 useTodos 中调用 useReducer

这里可能不是这种情况,但我发现人们在头脑中混合了很多东西,并将简单的东西变成了复杂的东西(比如 Redux = Context + useReducer)。

希望对您有所帮助!

直接在组件中使用useContext绝对没有问题。然而,它强制必须使用上下文值的组件知道要使用什么上下文。

如果您的应用程序中有多个要使用 TodoProvider 上下文的组件,或者您的应用程序中有多个上下文,您可以使用自定义挂钩稍微简化它

使用上下文时还必须考虑的另一件事是,您不应该在每次渲染时都创建一个新对象,否则所有使用 context 的组件都会重新渲染,即使什么都不会变了。为此,您可以使用 useMemo hook

const Context = React.createContext<{ todos: any; fetchTodos: any }>(undefined);

export const TodosProvider: React.FC<any> = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, null, init);
  const context = useMemo(() => {
    return {
      todos: state.todos,
      fetchTodos: async id => {
        const todos = await getTodos(id);
        console.log(id);
        dispatch({ type: "SET_TODOS", payload: todos });
      }
    };
  }, [state.todos, getTodos]);
  return <Context.Provider value={context}>{children}</Context.Provider>;
};

const getTodos = async id => {
  console.log(id);
  const response = await fetch(
    "https://jsonplaceholder.typicode.com/todos/" + id
  );
  return await response.json();
};
export const useTodos = () => {
  const todoContext = useContext(Context);
  return todoContext;
};
export const Todos = ({ id }) => {
  const { todos, fetchTodos } = useTodos();
  useEffect(() => {
    if (fetchTodos) fetchTodos(id);
  }, [id]);
  return (
    <div>
      <pre>{JSON.stringify(todos)}</pre>
    </div>
  );
};

Working demo

编辑:

Since getTodos is just a function that cannot change, does it make sense to use that as update argument in useMemo?

如果 getTodos 方法正在更改并在功能组件中调用,则将 getTodos 传递给 useMemo 中的依赖项数组是有意义的。通常,您会使用 useCallback 记住该方法,这样它就不会在每个渲染器上创建,而是仅当它从封闭范围更改的任何依赖项更改为更新其词法范围内的依赖项时才创建。现在在这种情况下,您需要将它作为参数传递给依赖项数组。

但是在你的情况下,你可以省略它。

Also how would you handle an initial effect. Say if you were to call `getTodos´ in useEffect hook when provider mounts? Could you memorize that call as well?

您只需在 Provider 中产生一个在初始挂载时调用的效果

export const TodosProvider: React.FC<any> = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, null, init);
  const context = useMemo(() => {
    return {
      todos: state.todos,
      fetchTodos: async id => {
        const todos = await getTodos(id);
        console.log(id);
        dispatch({ type: "SET_TODOS", payload: todos });
      }
    };
  }, [state.todos]);
  useEffect(() => {
      getTodos();
  }, [])
  return <Context.Provider value={context}>{children}</Context.Provider>;
};