简体   繁体   中英

React Context error on rendering

I created an app to learn ReactJS. Unfortunately, when I was trying to use context I got 1 error on rendering, but my app compiles well.

This is my code:

import React, {Component} from 'react';

const LoginContext = React.createContext(null);

const user = {
    isLoggedIn: true,
    username: 'test',
};

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoggedIn: false,
            user: user,
        };
    }

    render() {
        return (
            <LoginContext.Provider user={this.state.user}>
                 <Welcome/>
            </LoginContext.Provider>
        );
        }
    }

class Welcome extends Component {
    render() {
        return (
            <div>
                <WelcomeText/>
            </div>
        );
    }
}

class WelcomeText extends Component {
    render() {
        return (
            <LoginContext.Consumer>
                <div>
                    {(user) => (<p>{user.username}</p>)}
                </div>
            </LoginContext.Consumer>
        );
    }
}

export default App;

This is the error: updateContextConsumer http://localhost:3000/static/js/bundle.js:20927:23

  20924 | {
  20925 |   ReactCurrentOwner.current = workInProgress;
  20926 |   ReactDebugCurrentFiber.setCurrentPhase('render');
> 20927 |   newChildren = render(newValue);
        |                 ^  20928 |           ReactDebugCurrentFiber.setCurrentPhase(null);
  20929 | } // React DevTools reads this flag.
  20930 | 

Can you help me solve this?

ContextProvider needs a prop called value and not user

  <LoginContext.Provider value={this.state.user}>
        <Welcome/>
  </LoginContext.Provider>

Also the Context consumer has the children as a function and not the div

class WelcomeText extends Component {
    render() {
        return (
            <LoginContext.Consumer>
                  {(user) => (<div><p>{user.username}</p></div>)}
            </LoginContext.Consumer>
        );
    }
}

I am currently working on React-16.8.6 and having an interesting bug. I'm not sure if it's the known issue or not but I am having the same error whenever I have a space between two characters '}' and '<' as you can see it line-30.

After (1) removing the space or (2) completely making a new line with , it was resolved.

Even though I love React a lot, it's not perfect and we can make it better together.

有空间的时候

删除空间后

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM