Javascript 在本地存储全局变量后,如何访问它?

Javascript 在本地存储全局变量后,如何访问它?,javascript,jquery,reactjs,Javascript,Jquery,Reactjs,我在函数外使用局部变量时遇到问题。我正在调用myapi.com/access_token来获取访问令牌,然后我需要在我对jsonserverprovider的请求的头中使用该访问令牌。我已尝试使用window.bl_令牌声明它,但在尝试console.log响应时,仍然得到未定义的结果 import React from 'react'; import { fetchUtils, Admin, Resource } from 'react-admin'; import jsonServerPro

我在函数外使用局部变量时遇到问题。我正在调用myapi.com/access_token来获取访问令牌,然后我需要在我对jsonserverprovider的请求的头中使用该访问令牌。我已尝试使用window.bl_令牌声明它,但在尝试console.log响应时,仍然得到未定义的结果

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;
从“React”导入React;
从“react Admin”导入{fetchUtils,Admin,Resource};
从“ra数据json服务器”导入jsonServerProvider;
var bl_代币;
常量数据={email:'xxx@xxx.com,密码:'xxx'};
取('https://myapi.com/access_token', {
方法:“POST”,
标题:{
“内容类型”:“应用程序/json”,
},
正文:JSON.stringify(数据),
})
.then((response)=>response.json())
。然后((bl_数据)=>{
window.bl\u token=bl\u data.access\u token;
})
常量httpClient=(url,选项={})=>{
如果(!options.headers){
options.headers=新的头文件({Accept:'application/json'});
options.headers=新的头({Authorization:bl_token});
}
返回fetchUtils.fetchJson(url,选项);
};
const dataProvider=jsonServerProvider('https://myapi.com/,httpClient);
常量应用=()=>(
);
导出默认应用程序;

此处可能发生的情况是,当加载页面时,bl_令牌的初始值未定义,您设置获取令牌的功能将执行,但一旦完成并获取令牌,状态不会更新,在尝试获取时,bl_令牌将保持未定义状态

要解决这个问题,你需要让react监视状态的变化,我能想到的最简单的方法就是react钩子效应

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
}
import React,{useffect,useState}来自“React”;
从“react Admin”导入{fetchUtils,Admin,Resource};
从“ra数据json服务器”导入jsonServerProvider;
导出常量应用=()=>(
const[blToken,setBlToken]=useState(null);//将令牌置于react状态
常量数据={email:'xxx@xxx.com,密码:'xxx'};
//添加react钩子useEffect,这将在页面加载时触发
使用效果({
fetchData();
},[])
//将fetch移到函数中
常量fetchData=()=>{
取('https://myapi.com/access_token', {
方法:“POST”,
标题:{
“内容类型”:“应用程序/json”,
},
正文:JSON.stringify(数据),
})
.then((response)=>response.json())
。然后((bl_数据)=>{
//window.bl\u token=bl\u data.access\u token;
//在此处更新react状态
setBlToken(bl_数据.访问_令牌)
})
}
常量httpClient=(url,选项={})=>{
如果(!options.headers){
options.headers=新的头文件({Accept:'application/json'});
//在这里使用state变量
options.headers=新的头({Authorization:blToken});
}
返回fetchUtils.fetchJson(url,选项);
};
//仅当blToken存在时,添加一个用于渲染的检查
if(blToken){
const dataProvider=jsonServerProvider('https://myapi.com/,httpClient);
报税表(
)
}否则{
返回空
}
))


通过使用react的状态跟踪变量,当数据存在供您访问时,它可以重新呈现。

Var在任何用例中都不是正确的解决方案。在本例中,我将使用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>
 );
}
const-App=()=>{
常量[loaded,setLoaded]=React.useState(false);
const[accessToken,setAccessToken]=React.useState([]);
React.useffect(()=>{
//将获取放在这里(请注意以下是伪代码)
fetch('test')。然后(res=>res.json())。然后(res=>setAccessToken(res.token));
);
返回(
{已加载?您的逻辑依赖于SonaccessToken:null}
);
}

这里的示例中没有console.log。。。。