如何在Axios调用中创建上下文API [英] How to make a Context API inside an Axios Call
问题描述
我在mongodb上有一个React前端和一个Express后端.我已经设法加密了一个JWT令牌,现在我想将该同一个令牌传递到我的上下文状态中,因此我可以在其他组件中使用它来访问私有路由.出于某种原因,当我尝试在上下文api上设置state时,除非我将它与click事件一起直接使用,否则它根本不会更新.但是,当我收到Axios调用的响应时,我想更新上下文状态. //上下文
I have a react frontend and an express backend with mongodb. I have managed to encrypt a JWT token, and now I want to pass that same token into my context state , so I can use it in other components to access private routes. For some reason, when I try to setstate on the context api , it doesn't update at all unless I use it directly with a click event. However I would like to update the context state, when I get a response from an Axios call. // Context
const AuthProvider = props => {
const [token, setToken] = useState({
token: ""
});
const addToken = UserToken => {
setToken({ token: UserToken });
};
return (
<AuthContext.Provider value={{ token, addToken, setToken }}>
{props.children}
</AuthContext.Provider>
);
};
//axios调用位于一个名为this.UserSubscription
// The axios call is inside a function called this.UserSubscription
let self = this;
axios
.post(`http://localhost:5000/user/${page}`, {
username,
password
})
.then(function(res) {
userdata = res;
if (page === "login") {
self.setState({
isUser: true,
data: res
});
self.context.addToken(this.state.data);
}
console.log("hi world");
})
.catch(function(error) {
if (error.response) {
self.setState({
isError: true,
error: error.response.data.msg
});
}
});
<form onSubmit={this.UserSubscription} className="login-form">
<label>Username</label>
<input type="text" id="username" name="username" />
<label className="label-password">Password</label>
<input type="text" id="password" name="password" />
<p className="error-msg">{msg}</p>
<button
type="submit"
className="form-btn login-btn"
>
{this.props.title}
</button>
</form>
推荐答案
您未发布的代码肯定有问题,因为我可以重现您发布的代码,并且可以正常工作.
There must be something wrong with code you didn't post because I can reproduce the code you posted and it's working fine.
请注意,令牌位于context.token.token
const AuthContext = React.createContext();
const AuthProvider = ({ children }) => {
const [token, setToken] = React.useState({
token: '',
});
const addToken = token => setToken({ token });
return (
<AuthContext.Provider
value={{
token,
addToken,
}}
>
{children}
</AuthContext.Provider>
);
};
class ComponentOne extends React.Component {
constructor(props) {
super(props);
Promise.resolve().then(() =>
this.context.addToken('hello world')
);
}
render() {
return <div>in One: {JSON.stringify(this.context.token)}</div>;
}
}
ComponentOne.contextType = AuthContext;
const ComponentTwo = () => {
const { token } = React.useContext(AuthContext);
return <pre>in two: {JSON.stringify(token)}</pre>;
};
const App = () => (
<AuthProvider>
<ComponentOne />
<ComponentTwo />
</AuthProvider>
);
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
这篇关于如何在Axios调用中创建上下文API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!