反应-useContext返回未定义

时间:2020-08-18 19:21:09

标签: javascript reactjs react-context

我正在尝试使用React Context管理身份验证,但是我在PrivateRoute.js中看不到返回上下文的值

App.js

  render() {
  return (
    <>
    <BrowserRouter>
    <Islogin>
      <Header/>
    <Banner/>
     <Switch>
      <PrivateRoute exact path="/index" component={Landing} />
     <PrivateRoute path="/upload" component={Upload} exact />
     <PublicRoute restricted={false} path="/unauth" component={Unauthorized} exact  />
    </Switch>
    </Islogin>
    </BrowserRouter>
  
    </>
  );
}
}
export default App;

isAuthenticated的控制台日志返回未定义

PrivateRoute.js

const PrivateRoute = ({component: Component, ...rest}) => {
    const isAuthenticated  = useContext(AuthContext)
    console.log(isAuthenticated)
    const [validCredentials, setValidCredentials] = React.useState(false)
    React.useEffect(() => {
        if (typeof isAuthenticated === 'boolean') {
            setValidCredentials(isAuthenticated)
        }
    }, [isAuthenticated])
    return (
        // Show the component only when the user is logged in
        // Otherwise, redirect the user to /signin page
        <Route {...rest} render={props => (
            validCredentials  ?
                <Component {...props} />
            : <Redirect to="/unauth" />
        )} />
    );
};

export default PrivateRoute;

IsLogin.js

api调用有效,并且控制台日志显示为真。


export default function Islogin({ children }) {
    var [auth, setAuth] = React.useState(false)
   React.useEffect(() =>{
        axios.post('/api/auth').then(response => {
            var res = response.data.result;
            console.log("try")
            console.log(res)
            setAuth(res)
        })
    },[])
    
        return (
            <AuthContext.Provider value={auth}>
                {children}
            </AuthContext.Provider>
        )
}

1 个答案:

答案 0 :(得分:1)

您可能需要将其导入在(PrivateRoute.js)中使用它的文件的顶部

尝试一下:

import {useContext} from 'react'