【问题标题】:React - useContext returns undefinedReact - useContext 返回未定义
【发布时间】:2020-12-08 00:50:21
【问题描述】:

我正在尝试使用 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 的控制台日志返回 undefined

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 调用有效,控制台日志显示为 true。


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>
        )
}

【问题讨论】:

标签: javascript reactjs react-context


【解决方案1】:

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

试试这个:

import {useContext} from 'react'

【讨论】:

    猜你喜欢
    • 2019-12-24
    • 2023-04-06
    • 2021-07-19
    • 2019-12-13
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多