javascript - 如何以编程方式更改 React 上下文?

标签 javascript reactjs authentication react-context

我正在尝试使用新的 React 上下文来保存有关已登录用户的数据。

为此,我在名为 LoggedUserContext.js:

的文件中创建了一个上下文
import React from 'react';


export const LoggedUserContext = React.createContext(
  );

果然,现在我可以使用消费者访问其他组件中的所述上下文,例如我在此处所做的:

  <LoggedUserContext.Consumer>
       {user => (
       (LoggedUserContext.name) ? LoggedUserContext.name : 'Choose a user or create one';
       )}
   </LoggedUserContext.Consumer>

但很明显,为了让这个系统有用,我需要在登录后修改我的上下文,以便它可以保存用户的数据。我正在使用 axios 调用 REST API,我需要将检索到的数据分配给我的上下文:

axios.get(`${SERVER_URL}/users/${this.state.id}`).then(response => { /*What should I do here?*/});

我在 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,该值可以来自组件的状态并被更新

例如

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>
   }
}

关于dynamic context的部分解释一下

关于javascript - 如何以编程方式更改 React 上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49629953/

相关文章:

reactjs - 为 onClick 事件列出的函数在 ReactJS 上加载时触发

android - 如何实现在所有 Activity 中可用的登录 Activity 。安卓

javascript - 需要帮助在不使用 div id 的情况下使用 JavaScript 检索 anchor 文本

javascript - 请帮助理解功能

javascript - 跨上下文连接的网络音频 API 音频节点?

php - 使用 session 确保登录脚本安全

php - 无需用户身份验证的开发环境的 Symfony http 基本身份验证

javascript - jQuery magnific-popup : open 2 popup iframe with differents width/height

reactjs - 如何将来自 createApi 的查询结果存储在切片中?

javascript - 个别输入值不会改变