gpt4 book ai didi

javascript - React useState 钩子(Hook)没有像我预期的那样工作

转载 作者:行者123 更新时间:2023-12-03 00:00:31 27 4
gpt4 key购买 nike

我在 React 中使用 useState 钩子(Hook),但它的行为很奇怪。

如果你看看下面的例子,这就是我所期望的:调用login,成功后它会调用setRefreshToken(responseToken),然后调用refresh() 引用从 setRefreshToken 设置的 refreshToken。实际发生的情况是 refreshTokenrefresh() 内部未定义。

我知道 setState 是异步的,但我以前没有遇到过这样的问题。我错过了什么吗?

import React, { createContext, useState } from "react";
import jwtDecode from "jwt-decode";

const localStorageKey = "ar_refresh_token";

export const AuthContext = createContext();

export function AuthProvider({ tokenUrl, registerUrl, refreshUrl, children }) {
const [refreshToken, setRefreshToken] = useState(
window.localStorage.getItem(localStorageKey)
);

const [accessToken, setAccessToken] = useState();

const login = async (userId, password) => {
const response = await fetch(tokenUrl, {
method: "POST",
mode: "cors",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
userId,
password
})
});


if (response.status === 201) {
const token = await response.text();
setRefreshToken(token);
window.localStorage.setItem(localStorageKey, token);

await refresh();
}
};

const refresh = async () => {
const response = await fetch(refreshUrl, {
method: "POST",
mode: "cors",
headers: {
"Content-Type": "application/json",
Authorization: `JWT ${refreshToken}`
}
});


if (response.status === 201) {
const token = await response.text();
setAccessToken(token);
}
};

return (
<AuthContext.Provider
value={{
refreshToken,
accessToken,
login,
refresh
}}
>
{children}
</AuthContext.Provider>
);
}

完整示例:https://github.com/analyticsrequired/auth-admin/blob/master/src/AuthContext.js

最佳答案

您是对的,在调用 refresh 之前组件不会重新渲染,因此 refresh 内的 refreshToken 将是默认的。

您可以将 login 中的 token 作为参数传递给 refresh 并使用它,它将按预期工作。

const login = async (userId, password) => {
// ...
if (response.status === 201) {
// ...
await refresh(token);
}
};

const refresh = async refreshToken => {
const response = await fetch(refreshUrl, {
method: "POST",
mode: "cors",
headers: {
"Content-Type": "application/json",
Authorization: `JWT ${refreshToken}`
}
});

// ...
};

关于javascript - React useState 钩子(Hook)没有像我预期的那样工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55196851/

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