【问题标题】:How do I access a global variable after it has been stored locally?全局变量存储在本地后如何访问它?
【发布时间】:2020-03-04 13:30:15
【问题描述】:

我在使用函数外部的局部变量时遇到问题。我正在调用 myapi.com/access_token 以获取访问令牌,然后我需要在对 jsonserverprovider 的请求的标头中使用该访问令牌。我尝试使用 window.bl_token 声明它,但是当我尝试 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;

【问题讨论】:

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

标签: javascript jquery reactjs


【解决方案1】:

这里可能发生的情况是,当页面加载时,bl_token 的初始值未定义,您设置获取令牌的函数将被执行,但一旦完成并获得令牌,状态不会更新,离开bl_token 在您尝试获取时未定义。

要修复它,您需要对状态变化进行反应监视,我能想到的最简单的方法是反应钩子 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
}

);

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

【讨论】:

    【解决方案2】:

    在任何用例中,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>
     );
    }
    

    【讨论】:

      猜你喜欢
      • 2022-06-11
      • 2019-05-02
      • 2016-05-11
      • 2016-05-16
      • 2020-01-11
      • 2016-05-04
      • 2022-01-22
      • 2016-04-24
      • 2015-03-30
      相关资源
      最近更新 更多