如何以编程方式更改React上下文? [英] How to change React context programmatically?
问题描述
我正在尝试使用新的React上下文来保存有关已登录用户的数据.
I'm trying to use the new React context to hold data about the logged-in user.
为此,我在名为LoggedUserContext.js:
import React from 'react';
export const LoggedUserContext = React.createContext(
);
当然,现在我可以使用使用者访问其他组件中的所述上下文,例如我在这里所做的:
And sure enough, now I can get access to said context in other components using consumers, as I do here for example:
<LoggedUserContext.Consumer>
{user => (
(LoggedUserContext.name) ? LoggedUserContext.name : 'Choose a user or create one';
)}
</LoggedUserContext.Consumer>
但是显然,为了使该系统有用,我需要在登录后修改上下文,以便可以保存用户的数据.我正在使用axios调用REST API,并且需要将检索到的数据分配给我的上下文:
But obviously, for this system to be useful I need to modify my context after login, so it can hold the user's data. I'm making a call to a REST API using axios, and I need to assign the retrieved data to my context:
axios.get(`${SERVER_URL}/users/${this.state.id}`).then(response => { /*What should I do here?*/});
我在React的文档中看不到这样做的方法,但是他们甚至提到持有登录用户的信息是他们考虑到上下文的用例之一:
I see no way to do that in React's documentation, but they even mention that holding info of a logged in user is one of the use cases they had in mind for contexts:
上下文旨在共享可以被视为全局"的数据 一堆React组件树,例如当前经过身份验证的用户, 主题或首选语言.例如,在下面的代码中 手动穿过主题"道具以设置按钮样式 组件:
Context is designed to share data that can be considered "global" for a tree of React components, such as the current authenticated user, theme, or preferred language. For example, in the code below we manually thread through a "theme" prop in order to style the Button component:
那我该怎么办?
推荐答案
要使用Context
,您需要一个带有值的Provider
,该值可能来自组件的状态并被更新.
In order to use Context
, you need a Provider
which takes a value, and that value could come from the state of the component and be updated
例如
class App extends React.Component {
state = {
isAuth: false;
}
componentDidMount() {
APIcall().then((res) => { this.setState({isAuth: res}) // update isAuth })
}
render() {
<LoggedUserContext.Provider value={this.state.isAuth}>
<Child />
</LoggedUserContext.Provider>
}
}
关于动态上下文的部分
这篇关于如何以编程方式更改React上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!