我正在使用react的上下文API存储USER_TOKEN以便进行身份验证。
我还要在一个单独的模块中维护一个通用的提取功能,我想在其中使用此USER_TOKEN。
很明显,我不能在此模块内使用此USER_TOKEN,因为它不是React组件。
有什么办法可以在此提取函数中使用此USER_TOKEN。
成功登录后,我将USER_TOKEN存储到上下文API变量中。是的,我知道只要调用此函数,就可以从上下文传递变量。但问题是,将来的任何更改都必须在所有地方进行更改。所以我想知道是否只有一个地方可以做到这一点。基本上,这个想法是与所有API请求一起发送此令牌,因此尝试维护一个公共位置。
我们将不胜感激
df1 <- df %>%
mutate(DateTime = as.POSIXct(DateTime, format = "%d/%m/%Y %H:%M"),
Date = as.Date(DateTime)) %>%
arrange(DateTime) %>%
mutate(class = c("increase", "decrease")[(Area - lag(Area) < 0) + 1]) %>%
group_by(Date) %>%
mutate(prev_max = max(Area)) %>%
ungroup() %>%
mutate(prev_max = lag(prev_max)) %>%
group_by(Date) %>%
mutate(prev_max = first(prev_max)) %>%
ungroup
df1 %>%
mutate(prev_max = cummax(replace(prev_max, is.na(prev_max), 0)),
class = case_when(class == "increase" & Area > prev_max
& prev_max != 0 ~ "growth",
TRUE ~ class))
答案 0 :(得分:1)
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