How to change React context programmatically?

前端 未结 2 1865
难免孤独
难免孤独 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() {
           
               
           
       }
    }
    

    The section about dynamic context explains it

提交回复
热议问题