gpt4 book ai didi

javascript - 如何解决 Promise pending 的问题

转载 作者:行者123 更新时间:2023-12-02 02:04:13 26 4
gpt4 key购买 nike

我目前正在尝试在 React 中创建 protected 路由功能。我希望 result 将返回一个 bool 值而不是一个 promise ,而不会将 ProtectedRoute 更改为 async:

 import React from "react";
import { Redirect, Route } from "react-router-dom";
import { CheckToken } from "./RequestAction"

function ProtectedRoute({ component: Component, ...restOfProps }) {

const result = (async () => {
const res = await CheckToken()
return res;
})()

console.log(result); //log-> Promise {<pending>}[[Prototype]]: Promise[[PromiseState]]: "fulfilled"[[PromiseResult]]: false
return (
<Route
{...restOfProps}
render={(props) =>
result ? <Component {...props} /> : <Redirect to="/login/" />
}
/>
);
}


export default ProtectedRoute;

这是 CheckToken 函数:

 import axios from "axios";
async function CheckToken() {
let result = null;
await axios
.get(`http://localhost:5000/protected`,
{"withCredentials": true}
)
.then((res) => {
console.log("res.data.status:",res.data)
if (res.data.status === "success") {
result = true
}
})
.catch((err) => {
result = false
});
console.log("result:",result);
return result

}

最佳答案

const useToken = () => {
const [token, setToken] = useState(null);
useEffect(() => {
const f = async () => {
const res = await CheckToken();
//TODO: add check login;
setToken(res);
};
f();
})
return token;
}

function ProtectedRoute({ component: Component, ...restOfProps }) {
const token = useToken();
return (
<Route
{...restOfProps}
render={(props) =>
token ? <Component {...props} /> : <Redirect to="/login/" />
}
/>
);
}

函数组件主体不能是异步的。

关于javascript - 如何解决 Promise pending 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68663809/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com