简体   繁体   English

本地存储后如何访问全局变量?

[英]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.

相关问题 在TypeScript中,如何在本地更改全局变量的值? - In TypeScript, how do I change the value of a global variable locally? 如何检查Javascript全局对象是否已被篡改? - How do I check if the Javascript global object has been tampered with? 如何在没有全局变量的情况下访问此变量? - How do I access this variable without a global? 如何获得一个按钮被单击的次数的变量,将其在线存储然后在以后访问? - How do I get a variable of the number of times a button has been clicked, store it online and then access it later? 如何仅在异步代码块完成后访问 JavaScript 中的全局变量 - How do I access global variable in JavaScript only after asynch code block completes 如果requireJS模块在$上设置了全局变量,那么仅在分配了全局变量后,如何执行模块代码? - if a requireJS module sets a global on $, how do I execute the module code only when the global has been assigned? 在 Angular 中,如何访问在 iife 中初始化的全局变量? - In Angular how do I access a global variable that is initialized in an iife? 如何访问本地 scope 中的全局变量? - How do i access the global variable in local scope? 如何在不设置全局变量的情况下确定函数是否已被调用 - How to determine if a function has been called without setting global variable 如何显示本地存储的返回的道具值? - How do I display my returned props values that is stored locally?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM