useContext 不会在上下文更改时重新渲染组件

时间:2021-04-13 21:06:23

标签: reactjs typescript react-hooks use-context

我知道有几个帖子标题相同,但我想我已经检查了所有帖子,但没有一个(我发现的)适用于这种情况。

我有主文件的代码:

AuthContext:

import axios from "axios";
import React, { useEffect, useState } from "react"
import IUser from "../models/ILoggedUser";

export interface AuthContextProps {
  user: IUser | undefined,
  loginUser: (data: any) => void
}

const AuthContext = React.createContext<AuthContextProps>({
  user: undefined,
  loginUser: (data: any) => {}
});

function AuthProvider({children}: any) {

  const [authContext, setAuthContext] = useState<AuthContextProps>({
    user: undefined,
    loginUser
  });

  useEffect(() => {
    if (authContext?.user?.token) {
      axios.defaults.headers.common['Authorization'] = 'bearer ' + authContext?.user?.token;
    }
    console.log("changed authContext to: ", authContext)
  }, [authContext])

  useEffect(() => {
    console.log("changing authContext to: ", loadUserFromStorage(), authContext)
    setAuthContext({
      user: loadUserFromStorage(),
      loginUser
    });
  }, [])

  function loadUserFromStorage(): IUser | undefined {
    if(localStorage["loggedUser"] != undefined) {
      return JSON.parse(localStorage["loggedUser"]);
    }
    return undefined;
  }

  function loginUser(data: IUser): void {
    setAuthContext({
      user: data,
      loginUser
    });
  }

  return (
    <AuthContext.Provider value={authContext}>
          {children}
    </AuthContext.Provider>
  )
}

export { AuthProvider, AuthContext };

ProctedRoute:

import React, { useContext, useEffect, useState } from "react"
import { Redirect, Route, useHistory, useLocation } from "react-router";
import { AuthContext } from "../contexts/AuthContext";

interface ProtectedRouteProps {
  Component: () => JSX.Element;
  path: string;
} 

const ProtectedRoute = ({Component, path}: ProtectedRouteProps) => {
  const authContext = useContext(AuthContext);

  useEffect(() => {
    console.log("CHANGE: ", authContext)
  }, [authContext])

  return (
    <Route
      path={path}
      render={props =>
        (authContext?.user) ?
          <Component /> :
          <Redirect to={{ pathname:"/login" }}/>
      }
      />
  )
}

export default ProtectedRoute;

应用:

import React, { useContext, useEffect, useState } from "react"
import { Redirect, Route, useHistory, useLocation } from "react-router";
import { AuthContext } from "../contexts/AuthContext";

interface ProtectedRouteProps {
  Component: () => JSX.Element;
  path: string;
} 

const ProtectedRoute = ({Component, path}: ProtectedRouteProps) => {
  const authContext = useContext(AuthContext);

  useEffect(() => {
    console.log("CHANGE: ", authContext)
  }, [authContext])

  return (
    <Route
      path={path}
      render={props =>
        (authContext?.user) ?
          <Component /> :
          <Redirect to={{ pathname:"/login" }}/>
      }
      />
  )
}

export default ProtectedRoute;
  • 将 AuthContext 设置为新对象,而不是改变现有状态 - 已检查
  • 中包含所有内容 - 已检查
  • 应该重新渲染的组件中包含“useContext” - 已检查

但是当我将AuthContext 设置为新值时,ProtectedRoute 不会重新渲染 -> 谁能给我建议为什么? 整个代码可在 github (https://github.com/Dan102/task_manager_clone/tree/master/task-manager-client/src) 上找到

0 个答案:

没有答案