How to change React context programmatically?

为君一笑 提交于 2020-01-01 03:00:24

问题


I'm trying to use the new React context to hold data about the logged-in user.

To do that, I create a context in a file called 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.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:

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:

So how can I do it?


回答1:


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

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 context explains it




回答2:


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 docs for an example with better component composition.



来源:https://stackoverflow.com/questions/49629953/how-to-change-react-context-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!