javascript 如何以编程方式更改 React 上下文?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49629953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change React context programmatically?
提问by kace91
I'm trying to use the new React context to hold data about the logged-in user.
我正在尝试使用新的 React 上下文来保存有关登录用户的数据。
To do that, I create a context in a file called LoggedUserContext.js:
为此,我在名为的文件中创建了一个上下文 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>
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 调用 REST API,我需要将检索到的数据分配给我的上下文:
axios.get(`${SERVER_URL}/users/${this.state.id}`).then(response => { /*What should I do here?*/});
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 旨在共享可被视为 React 组件树的“全局”数据,例如当前经过身份验证的用户、主题或首选语言。例如,在下面的代码中,我们手动遍历“主题”道具以设置 Button 组件的样式:
So how can I do it?
那么我该怎么做呢?
回答by Shubham Khatri
In order to use Context, you need a Providerwhich takes a value, and that value could come from the state of the component and be updated
为了使用Context,您需要一个Provider接受一个值的值,该值可以来自组件的状态并被更新
for instance
例如
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>
}
}
The section about dynamic contextexplains it
关于动态上下文的部分解释了它
回答by Hinrich
Wrap your consuming component in a provider component:
将您的消费组件包装在提供程序组件中:
import React from 'react';
const SERVER_URL = 'http://some_url.com';
const LoggedUserContext = React.createContext();
class App extends React.Component {
state = {
user: null,
id: 123
}
componentDidMount() {
axios.get(`${SERVER_URL}/users/${this.state.id}`).then(response => {
const user = response.data.user; // I can only guess here
this.setState({user});
});
}
render() {
return (
<LoggedUserContext.Provider value={this.state.user}>
<LoggedUserContext.Consumer>
{user => (
(user.name) ? user.name : 'Choose a user or create one';
)}
</LoggedUserContext.Consumer>
</LoggedUserContext.Provider>
);
}
}
I gave a complete example to make it even clearer (untested). See the docsfor an example with better component composition.
我给出了一个完整的例子,让它更清楚(未经测试)。有关更好的组件组合的示例,请参阅文档。

