简体   繁体   中英

React function not returning any value

I'm currently using firebase to populate a website with a certain user's first and last name, but for some reason it isn't working.

getUserName(){
    firebaseAuth().onAuthStateChanged((user) => {
        if(user){
            // var name = ref.ref('users/' + user.uid).once('value').then((snapshot) => console.log(snapshot.val().displayName));
            var name = user.displayName;
            console.log("name in function: " + name); //prints full name
            return name;
        }
    });
}


render() {
    var name = this.getUserName();
    console.log("name: " + name); //prints undefined
    return (
        <div className="col-sm-6 col-sm-offset-3">
            <h1> Welcome {this.getUserName()} asdfasd </h1>
        </div>
    );
}

These are my two functions. For some reason, when I print out the name variable in both cases, I get two different variables. In getUserName(), it prints out the user's full name, and I then return that value. When the DOM renders, the "name" variable is undefined even though the getUserName() function prints out the full name. Any help would be greatly appreciated!

Your method getUserName() doesn't actually return anything, so when you try to assign its return value to the name -variable, like this var name = this.getUserName(); , you'll always just set name to undefined .

As Shailesh Prajapati suggests, you should set the name in the component state. I would even argue, you should separate it out to a global state using something like Redux. Also, you shouldn't call this.getUserName() within the render() function, as it could (and most likely will) be very bad for performance.

Here's the code, with everything suggested:

componentWillMount(){
    this.getUserName();
}

getUserName(){
    firebaseAuth().onAuthStateChanged((user) => {
        if(user){
            var name = user.displayName;
            this.setState({ name: name });
        }
    });
}

render() {
    return (
        <div className="col-sm-6 col-sm-offset-3">
            <h1> Welcome {this.state.name} asdfasd </h1>
        </div>
    );
}

You Have to use State instead of variable.Store name value in this.SetState({name: value}) and use directly using this.state.name where ever you want to use...

Local variable cannot access from outside function so you have to use state in react to access state/variable outside the function..

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