我正在使用“expo-secure-store”来存储 JWT 令牌。当我尝试首先获取数据时,它什么也没有返回,然后是令牌。
我的代码:
const [api, ApiReply] = React.useState("");
const [isLoading, setLoading] = useState(true);
const [token, setToken] = React.useState("");
const clickHandler = () => {
SecureStore.getItemAsync("secure_token").then((token) => setToken(token));
console.log(token);
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer " + token);
var requestOptions = {
method: "GET",
headers: myHeaders,
};
fetch("http://193.119.10.206:3000/auth/user/8", requestOptions)
.then((response) => response.text())
.then((result) => ApiReply(JSON.parse(result)))
.catch((d) => {
alert("500");
})
.finally(() => setLoading(false));
};
React.useEffect(() => {
clickHandler();
}, [api])
渲染时我需要令牌。有什么解决办法或者其他方法吗?
您可以通过三种方式执行此操作:
移动
then
闭合内的所有内容。这将等待您的 get 异步函数完成,然后再对令牌执行任何操作。
const clickHandler = () => {
SecureStore.getItemAsync("secure_token").then((token) => {
setToken(token);
console.log(token);
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer " + token);
var requestOptions = {
method: "GET",
headers: myHeaders,
};
fetch("http://193.119.10.206:3000/auth/user/8", requestOptions)
.then((response) => response.text())
.then((result) => ApiReply(JSON.parse(result)))
.catch((d) => {
alert("500");
})
.finally(() => setLoading(false));
});
};
使用
await
代替:
const clickHandler = async () => {
const token = await SecureStore.getItemAsync("secure_token");
setToken(token);
console.log(token);
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer " + token);
var requestOptions = {
method: "GET",
headers: myHeaders,
};
fetch("http://193.119.10.206:3000/auth/user/8", requestOptions)
.then((response) => response.text())
.then((result) => ApiReply(JSON.parse(result)))
.catch((d) => {
alert("500");
})
.finally(() => setLoading(false));
};
利用useEffect:
const clickHandler = ()=>{
SecureStore.getItemAsync("secure_token").then((token) => setToken(token));
}
useEffect(()=>{ if(token !== null) { //call fetch } },[token])