首页 > 解决方案 > ReactJs,如何等待我的函数返回一些东西

问题描述

我有一个函数调用 isAuthenticated 来检查令牌的有效性:

isAuthenticated = async () => {

        const data = await request.call({
            url: `http://localhost:1337/utilisateurs/VerifyUserTok`,
            method: `post`,
            parameters : {
                authorization: `bearer ${sessionStorage.getItem(`token`)}`
            }
        });

        if (data.IsValide){
            return true;
        } else {
            return false;
        }
    }

在我的受保护路线中,如果前一个函数返回 false,我不会重定向此人。但是在 protected.route.js 文件中,该函数在第一次返回时无需等待我的 isAuthenticated 函数返回一些东西:

import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import auth from './auth.js'
import NavMenu from './NavMenu';

export const ProtectedRoute = ({ component: Component, ...rest }) => {
    return (
        <Route 
            {...rest} 
            render = {props => {
                if(auth.isAuthenticated()){
                    return <div className="page-body">
                                <Route>
                                    <NavMenu/>
                                    <div className="right-body">
                                        <Component {...props}/>
                                    </div>
                                </Route>
                            </div>
                } else {
                    return <Redirect to={
                        {
                            pathname: "/",
                            state: {
                                from: props.location
                            }
                        }     
                    } />
                }

            }}
        />
    );
}

标签: javascriptreactjs

解决方案


您将需要一些状态来保存您正在寻找的信息,并且您需要在效果中执行身份验证查找。

当然,您可能会选择在进行身份验证检查时使用某种方式来显示加载指示器,但您可以根据需要找出该机制。

import React, { useState, useEffect } from 'react';
import { Route, Redirect } from 'react-router-dom';
import auth from './auth.js'
import NavMenu from './NavMenu';

export const ProtectedRoute = ({ component: Component, ...rest }) => {
    const [isAuthed, setIsAuthed] = useState(false);
    const [isLoaded, setIsLoaded] = useState(false);

    // Assuming you just want to check on initial render
    useEffect(() => {
      let mounted = true;
      const checkAuth = async () => {
        const authed = await auth.isAuthenticated();
        if (mounted) {
          setIsAuthed(authed);
          setIsLoaded(true);
        }
      checkAuth();
      return () => {
        mounted = false;
      }
    }, [])

    return !isLoaded ? "Loading..." : (
        <Route 
            {...rest} 
            render = {props => {
                if(isAuthed){
                    return <div className="page-body">
                                <Route>
                                    <NavMenu/>
                                    <div className="right-body">
                                        <Component {...props}/>
                                    </div>
                                </Route>
                            </div>
                } else {
                    return <Redirect to={
                        {
                            pathname: "/",
                            state: {
                                from: props.location
                            }
                        }     
                    } />
                }

            }}
        />
    );
}

推荐阅读