React 类如何在 promise 获取调用后返回布尔值



你好,当我从 react 中的另一个组件调用 Auth.isAuthenticated(( 时,我有这个类,它总是返回 false(这是默认值(,即使服务器返回 200 响应,女巫也会设置这个。如何使用 promise 使方法等到获取调用完成,然后返回结果

编辑:我需要返回布尔值 true 或 false,因此基于此,我可以显示或隐藏组件,所有答案都有帮助,但我需要一个布尔值而不是承诺任何帮助

    class Auth {
    constructor() {
        this.authenticated = false;
    }

    isAuthenticated() {
        //get token from local storage if there is one
        const jwttoken = localStorage.getItem('jwttoken');
        const bearer = 'Bearer ' + jwttoken;
        const data = new FormData();
        // get the website backend main url from .env
        const REACT_APP_URL = process.env.REACT_APP_URL
        fetch(`${REACT_APP_URL}/api/auth/verify`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Authorization': bearer,
            },
            body: data
        }).then(
            (response) => {
                response.json()
                    .then((res) => {
                        if (response.status === 200) {
                            this.authenticated = true;
                        }
                        if (response.status === 401) {
                            localStorage.removeItem('jwttoken');
                            this.authenticated = false;
                        }
                    })
            }
        ).catch((err) => {
            // console.log(err)
        });
        return this.authenticated;
    }

}

export default new Auth();

从另一个组件调用 Auth.isAuthenticated(( === true

export const PrivateRoute = ({ component: Component, ...rest }) => {
  return (
    <Route {...rest} render={(props) => (
      Auth.isAuthenticated() === true
        ? <Component {...props} />
        : <Redirect to='/admin' />
    )} />
      )
}

假设您要编写一个函数,该函数返回一个 promise,并在某些操作完成时进行解析(例如 API 调用(。你可以写这样的东西:

const myAsyncFunction = () =>{
    return new Promise((resolve, reject) =>{
        //Faking an API Call
        setTimeout(() => resolve('data'), 400)
    })
}

给你!现在你有一个函数,它返回一个承诺,该承诺将在 400 毫秒内解析。现在,您需要使用.then()方法或async await语句。

const sideEffects = async () =>{
    const result = await myAsyncFunction()
    console.log(result) //'data'
}
如果你

不想做async/await你可以让isAuthenticated回报一个承诺。

isAuthenticated() {
  return new Promise((resolve, reject) => {
    //get token from local storage if there is one
        const jwttoken = localStorage.getItem('jwttoken');
        const bearer = 'Bearer ' + jwttoken;
        const data = new FormData();
        // get the website backend main url from .env
        const REACT_APP_URL = process.env.REACT_APP_URL
        fetch(`${REACT_APP_URL}/api/auth/verify`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Authorization': bearer,
            },
            body: data
        }).then(
            (response) => {
                response.json()
                    .then((res) => {
                        if (response.status === 200) {
                            resolve(true)
                        }
                        if (response.status === 401) {
                            localStorage.removeItem('jwttoken');
                            resolve(false)
                        }
                    })
            }
        ).catch((err) => {
            // reject(err)
        });
  })        
}

在异步函数中,您可以执行let isAuthenticated = await isAuthenticated()或者您可以使用异步函数之外的.then.catch返回结果

使用 await async

async isAuthenticated() {
        //get token from local storage if there is one
        const jwttoken = localStorage.getItem('jwttoken');
        const bearer = 'Bearer ' + jwttoken;
        const data = new FormData();
        // get the website backend main url from .env
        const REACT_APP_URL = process.env.REACT_APP_URL
        const response = await fetch(`${REACT_APP_URL}/api/auth/verify`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Authorization': bearer,
            },
            body: data
        });
        const responseToJson = await response.json();
         if (responseToJson.status === 200) {
             this.authenticated = true;
         }
         if (responseToJson.status === 401) {
             localStorage.removeItem('jwttoken');
             this.authenticated = false;
         }
       return this.authenticated;
    }

最新更新