[英]How do I access a global variable after it has been stored locally?
I am having issues using a local variable outside of the function.我在使用函数外的局部变量时遇到问题。 I am making a call to myapi.com/access_token to obtain the access token and then I need to use that access token in the header of my request to the jsonserverprovider.我正在调用 myapi.com/access_token 以获取访问令牌,然后我需要在我对 jsonserverprovider 的请求的标头中使用该访问令牌。 I have tried declaring it with window.bl_token but I still get a result of undefined when I attempt to console.log the response.我试过用 window.bl_token 声明它,但是当我尝试 console.log 响应时,我仍然得到 undefined 结果。
import React from 'react';
import { fetchUtils, Admin, Resource } from 'react-admin';
import jsonServerProvider from 'ra-data-json-server';
var bl_token;
const data = { email: 'xxx@xxx.com', password: 'xxx' };
fetch('https://myapi.com/access_token', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((bl_data) => {
window.bl_token=bl_data.access_token;
})
const httpClient = (url, options = {}) => {
if (!options.headers) {
options.headers = new Headers({ Accept: 'application/json' });
options.headers = new Headers({Authorization: bl_token});
}
return fetchUtils.fetchJson(url, options);
};
const dataProvider = jsonServerProvider('https://myapi.com/', httpClient);
const App = () => (
<Admin dataProvider={dataProvider}>
<Resource name="links"/>
</Admin>
);
export default App;
Potentially what is happening here is that when the page is loaded the initial value of bl_token is undefined, your function to set fetch the token will be executing but once this is completed and the token is obtained the state is not updated, leaving bl_token as undefined when you try and obtain it.这里可能发生的情况是,当页面加载时 bl_token 的初始值未定义,您设置获取令牌的函数将执行,但是一旦完成并获得令牌,状态不会更新,将 bl_token 保留为未定义当您尝试获得它时。
To fix it you will need to have react watch for the state change, the easiest way I can think of would be the react hook useEffect.要修复它,您需要对状态变化进行反应观察,我能想到的最简单的方法是反应钩子 useEffect。
import React, { useEffect, useState } from 'react';
import { fetchUtils, Admin, Resource } from 'react-admin';
import jsonServerProvider from 'ra-data-json-server';
export const App = () => (
const [blToken, setBlToken] = useState(null); // chuck the token in react state
const data = { email: 'xxx@xxx.com', password: 'xxx' };
// add the react hook useEffect, this will fire on page load
useEffect({
fetchData();
},[])
// move the fetch into a function
const fetchData = () => {
fetch('https://myapi.com/access_token', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((bl_data) => {
//window.bl_token=bl_data.access_token;
// update the react state here
setBlToken(bl_data.access_token)
})
}
const httpClient = (url, options = {}) => {
if (!options.headers) {
options.headers = new Headers({ Accept: 'application/json' });
// use the state variable here
options.headers = new Headers({Authorization: blToken});
}
return fetchUtils.fetchJson(url, options);
};
// add a check to render only if the blToken is present
if(blToken) {
const dataProvider = jsonServerProvider('https://myapi.com/', httpClient);
return(
<Admin dataProvider={dataProvider}>
<Resource name="links"/>
</Admin>
)
} else {
return null
}
); );
By using react's state to keep track of the variable it can re render when the data is present for you to access.通过使用 react 的状态来跟踪变量,它可以在数据存在时重新呈现供您访问。
Var is never the right solution in any use case.在任何用例中,Var 都不是正确的解决方案。 In this example I would use the useEffect function that comes with react:在这个例子中,我将使用 react 自带的 useEffect 函数:
const App = () => {
const [loaded, setLoaded] = React.useState(false);
const [accessToken, setAccessToken] = React.useState([]);
React.useEffect(() => {
// put your fetch here (please be aware that the following is pseudo code)
fetch('test').then(res => res.json()).then(res => setAccessToken(res.token));
);
return (
<div>
{loaded ? yourLogicThatDependsOnAccessToken : null }
</div>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.