How to change React context programmatically?

前端 未结 2 1864
难免孤独
难免孤独 2021-02-07 07:15

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:

相关标签:
2条回答
  • 2021-02-07 07:44

    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

    0 讨论(0)
  • 2021-02-07 08:00

    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.

    0 讨论(0)
提交回复
热议问题