How to change React context programmatically?

前端 未结 2 1858
难免孤独
难免孤独 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 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 (
                
                    
                        {user => (
                            (user.name) ? user.name : 'Choose a user or create one';
                        )}
                    
                
            );
        }
    }
    

    I gave a complete example to make it even clearer (untested). See the docs for an example with better component composition.

提交回复
热议问题