反应-如何等待直到api调用完成才能加载路径?

问题描述

如果用户有权访问应用程序,我会使用axios帖子向后端请求。问题是axios返回undefined,然后返回true或false。有一个私有路由来管理在万一返回true或false(在这种情况下,undefined = false)的情况下该怎么做,axios是问题所在还是还有其他解决方法?就像等到返回true或false

IsLogin.jsx

import React from 'react'
const axios = require('axios');
export const AuthContext = React.createContext({})

export default function Islogin({ children }) {
   const isAuthenticated =()=>{
       try{
            axios.post('/api/auth').then(response => {
               var res = response.data.result;
               console.log(res)
               return res
           })
       } catch (error) {
           console.error(error);
           return false
       }

   }
  
   var auth = isAuthenticated()
   console.log(auth);
   return (
       <AuthContext.Provider value={{auth}}>
           {children}
       </AuthContext.Provider>
   )
}

privateRoute.js

import React,{ useContext } from 'react';
import { Route,Redirect } from 'react-router-dom';
import  {AuthContext}  from '../utils/IsLogin';

const PrivateRoute = ({component: Component,...rest}) => {

   const {isAuthenticated}  = useContext(AuthContext)
   
   return (

       // Show the component only when the user is logged in
       // Otherwise,redirect the user to /unauth page
       <Route {...rest} render={props => (
           isAuthenticated ?
               <Component {...props} />
           : <Redirect to="/unauth" />
       )} />
   );
};
export default PrivateRoute; 

app.js

class App extends Component {
  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>
  
    </>
  );
}
}

解决方法

我很好奇你为什么不使用'async await',大声笑。

您正在向端点'/ api / auth'发出发布请求,但没有向其提供任何要发布的数据,例如:

try{
       axios.post('/api/auth',{username,password}).then(response => {
           var res = response.data.result;
           console.log(res)
           return res
       })
       } catch (error) {
           console.error(error);
           return false
       }
,

您不想在发帖请求中返回任何内容。您应该更新自己的上下文存储

const isAuthenticated = () => {
    try {
        axios.post('/api/auth').then(response => {
            var res = response.data.result;
            console.log(res)
            // update your context here instead of returning
            return res
        })
    } catch (error) {
        console.error(error);
        return false
    }
}

在您的私人路线中,具有componentDidUpdate样式的useEffect钩子可检查身份验证状态的更改并根据需要更新内部标志

const PrivateRoute = ({ component: Component,...rest }) => {
    const { isAuthenticated } = useContext(AuthContext)
    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 /unauth page
        <Route {...rest} render={props => (
            validCredentials ?
                <Component {...props} />
                : <Redirect to="/unauth" />
        )} />
    );
};