问题
I am using react's context API for storing USER_TOKEN for authentication purposes.
Also I am maintaining a common fetch function in a separate module where I want to use this USER_TOKEN.
And Its obvious that I cannot use this USER_TOKEN inside this module as it is not a react component.
Is there any way I can use this USER_TOKEN inside this fetch function.
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.
Help would be appreciated
Fetch Module
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();
}
}
回答1:
- create a folder named: Context in the src/components folder
- in this folder that you have created (Context ) create a file named index.js
- in the index.js file write:
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;
- in the src/index.js:
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")
);
- let's say you have login component, in it write down:
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
来源:https://stackoverflow.com/questions/57551741/how-to-use-reacts-context-api-outside-of-reacts-component-scope-reactjs