reactjs 为什么组件使用上下文,总是重新渲染?

9rygscc1  于 2023-04-11  发布在  React
关注(0)|答案(1)|浏览(134)

我有个问题要问
下面是我的代码

const { getValueFromKey, setValueToLocal, removeValueStorage } = useStorage<AuthStateValue>();
 const [state, setState] = useState<AuthStateValue>({ ...initialValue });

 const handleLogin = () => {
   const dataFromLocal = getValueFromKey('user-info');
   setState({ ...dataFromLocal, isAuth: true });
   setValueToLocal('access-token', state.accessToken);
 };

 const handleLogout = () => {
   setState(initialValue);
   removeValueStorage('user-info');
 };

 const userInfo = useMemo(() => ({ ...state }), [state]);
 const login = useCallback(() => handleLogin(), [handleLogin]);
 const logout = useCallback(() => handleLogout(), [handleLogout]);

 return (
   <AuthContext.Provider value={{ state: { ...userInfo }, login, logout }}>
      {children}
   </AuthContext.Provider>
 );
};`

在我的组件中

const { login, state } = useContext(AuthContext);

我在使用context的时候,尽管有记忆的价值,但是子组件总是会重新渲染。有人能帮我解释一下吗?
帮助我澄清React中上下文和备忘录

8fq7wneg

8fq7wneg1#

您需要记住传递给提供者的整个value,这样它的标识就不会改变;就像这样
这些函数也是memoized的(使用useCallback),所以它们也不会改变每个渲染。

function Component() {
  const { getValueFromKey, setValueToLocal, removeValueStorage } = useStorage<AuthStateValue>();
  const [state, setState] = useState<AuthStateValue>({ ...initialValue });

  const handleLogin = useCallback(() => {
    const dataFromLocal = getValueFromKey("user-info");
    setState({ ...dataFromLocal, isAuth: true });
    setValueToLocal("access-token", state.accessToken);
  }, [/* TODO */]);

  const handleLogout = useCallback(() => {
    setState(initialValue);
    removeValueStorage("user-info");
  }, [/* TODO */]);

  const value = useMemo(() => ({ state, login, logout }), [state, login, logout]);

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

相关问题