如何在React的组件范围之外使用React的上下文API:ReactJS [英] How to use React's context API outside of react's component scope : ReactJS

查看:149
本文介绍了如何在React的组件范围之外使用React的上下文API:ReactJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用react的上下文API来存储USER_TOKEN以进行身份​​验证。

I am using react's context API for storing USER_TOKEN for authentication purposes.

我还在一个单独的模块中维护一个通用的提取函数,我想在其中使用此USER_TOKEN 。

Also I am maintaining a common fetch function in a separate module where I want to use this USER_TOKEN.

很明显,我不能在此模块内使用此USER_TOKEN,因为它不是React组件。

And Its obvious that I cannot use this USER_TOKEN inside this module as it is not a react component.

有什么办法可以在此提取函数中使用此USER_TOKEN。

Is there any way I can use this USER_TOKEN inside this fetch function.

成功登录后,我将USER_TOKEN存储到上下文API变量中。是的,我知道只要调用此函数,就可以从上下文传递变量。但问题是,未来的任何变化都必须在所有地方进行改变。所以我想知道是否只有一个地方可以做到这一点。基本上,这个想法是与所有API请求一起发送此令牌,因此尝试维护一个公共位置。

I am storing USER_TOKEN into a context API variable after successful sign-in. Yes I know we could pass the variable from context whenever we call this function. But the thing is , Any change in the future will have to change it in all places. So I was wondering If there is only one place where I can do this. Basically the idea is sending this token along with all the API requests, so trying to maintain a common place.

我们将不胜感激


export module FetchModule {
  export async function fetch(obj: any) {
    let url = obj.url;
    let type = obj.type ? obj.type.toUpperCase() : "GET";
    let options: any = {};
    options.method = type;
    let idToken = obj.token;// Want to retrieve this USER_TOKEN from react's context API 
    if (idToken) {
      options.headers["USER_TOKEN"] = idToken;
    }
    options.headers = { ...options.headers, ...obj.headers };
    const response = await fetch(url, options);
    return await response.json();
  }
}


推荐答案


  • 在src / components文件夹中创建一个名为:Context的文件夹

  • 在已创建的该文件夹中(Context)创建一个名为index.js的文件

  • 在index.js文件中写入:

  • import React, { Component } from 'react';
    
    const AppContext = React.createContext();
    
    export class Provider extends Component {
    
    
      state = {
        
          token: ''
        
      };
      
      setToken = (token) => {
      
        this.state.token = token;
        this.setState();
      
      };
      
      render() {
      
        return (
          
            <AppContext.Provider value = {{ 
        
                    token: this.state.token,
                    actions: {
                      setToken: this.setToken
                    }
    
            }}>
        
            {this.props.children}
          </AppContext.Provider>
      
          );
        
      
      }
    
    }
    
    exoprt const Consumer = AppContext.Consumer;
    export const AppContextObject = AppContext;



    import React from 'react';
    import ReactDOM from 'react-dom';
    import { Provider } from "./compomemts/Context/";
    import App from './App';
    
    ReactDOM.render(
        <Provider>
            <App  />
        </Provider>
        , document.getElementById("root")
    );


    • 假设您有登录组件,在其中写下:

    import React, { PureComponent } from 'react';
    import { Consumer, AppContextObject } from "../Context";
    
    class Login extends PureComponent { 
    
    
    
    render() {
    
      return (
      
        <Consumer>
          {(actions, token) => (
          
            <button className="enter" id="enter-id" onClick={(event) => {
              if(token === undifined) {
                newToken = 'get the token from your system';
                actions.setToken(newToken);
              }
              
            }} >
                                    connect
                                </button>
          
          )}
        </Consumer>
    
      )
    
    }
    
    
    
    }
    
    Login.contextType = AppContextObject; // This part is important to access context values

    SuperAdminContextObject

    这篇关于如何在React的组件范围之外使用React的上下文API:ReactJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆