希望你做得很好 :)
我有一个“auth.js”文件,其中有一个 aysnc 函数来获取userId,然后将其存储在会话存储中。这里是:
export let userId = sessionStorage.getItem("userId");
const getUserId = async () => {
if (token) {
await axios
.get(`${baseURL}/auth/user`, {
headers: {
authorization: token
}
})
.then(function (response) {
const { data } = response;
return sessionStorage.setItem("userId", data.userId);
})
.catch(function (err) {
return undefined;
});
}
};
getUserId();
Run Code Online (Sandbox Code Playgroud)
然后我在所有需要它的组件中访问该变量,以便发出其他请求。App.js 中的示例:
useEffect(() => {
getActiveGames();
if (token && userId) {
getCart();
getWallet();
getWalletPayments();
}
}, []);
Run Code Online (Sandbox Code Playgroud)
问题是,在第一次渲染中,userId 为空(显然),我正在尝试不同的方法来更新甚至重新渲染,以便获得更新的值,但似乎没有任何效果。我知道有一个基本的解决方案,但我就是想不出来。
如果你能帮忙那就太好了:)
希望你们在这种情况下一切顺利:) 在 React 应用程序的 App 组件中运行渲染测试时,我在 useContext 中遇到错误。
这是上下文 api:
const { userId } = useContext(UserContext);
这是错误:
TypeError:无法解构“(0,_react.useContext)(...)”的属性“userId”,因为它未定义。
35 | 35 const { userId } = useContext(UserContext);
该对象一开始是未定义的,因为它是获取 userId 的 API 调用。登录后,用户 ID 可用。因此,在开发中运行时,它可以正常工作,但在运行测试时,它会显示此错误。
最后是 UserContext 组件:
导出 const UserContext = createContext();
const UserProvider = ({ children }) => {
const [userId, setUserId] = useState("");
const getUserId = async () => {
if (token) {
await axios
.get(`${baseURL}/auth/user`, {
headers: {
authorization: token
}
})
.then(function …Run Code Online (Sandbox Code Playgroud)unit-testing reactjs jestjs react-testing-library use-context