我有一个关于上下文的问题
下面是我的代码
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);
当我使用上下文时,尽管有记忆值,但子组件总是重新呈现。有人能帮我解释一下吗?帮助我澄清react中的上下文和记忆
你需要记住你传递给提供者的整个value
,这样它的身份就不会改变;像这样。
函数也被记忆(与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>;
}