无法在reactJS中设置setstate

无法在reactJS中设置setstate,reactjs,firebase,Reactjs,Firebase,有人能解释一下我做错了什么吗?我的setState控制台返回的是未定义的,而第一个控制台返回的是正确的值 return firebase.database().ref('Users/Trainers/').on('value', (snapshot) => { snapshot.forEach(function(childSnapshot){ // var childKey= childSnapshot.key;

有人能解释一下我做错了什么吗?我的setState控制台返回的是未定义的,而第一个控制台返回的是正确的值

return firebase.database().ref('Users/Trainers/').on('value', (snapshot) => {
            snapshot.forEach(function(childSnapshot){
                // var childKey= childSnapshot.key;
                var childData= childSnapshot.val();
                var childEmail = childData.email;
                var childfirstName = childData.firstName;
                var childlastName = childData.lastName;
                var childTrainers = childfirstName + ' ' + childlastName + ' ' + childEmail;
                 console.log(childTrainers);
            })
            this.setState({
                Trainers: snapshot.val().childTrainers
            })
            console.log(this.state.Trainers)
        })

好的,我做了,正确的答案是

return firebase.database().ref('Users/Trainers/').on('value', (snapshot) => {
            snapshot.forEach((childSnapshot) => {
                // this.setState({
                //     childEmail = childSnapshot.val().email
                // })
                // var childKey= childSnapshot.key;
                var childData= childSnapshot.val();
                var childEmail = childData.email;
                var childfirstName = childData.firstName;
                var childlastName = childData.lastName;
                var childTrainers = childfirstName + ' ' + childlastName + ' ' + childEmail;
                 //console.log(childTrainers);
                 this.setState({
                     Trainers: [childTrainers]
                 }, console.log(this.state.Trainers))
            })
        })

正在检索的所有值

设置状态
是异步的,您不能在下一行记录它。使用
setState
中的第二个参数,这是一个回调,您可以在其中访问udpated state感谢我的理解,我这样做就像
this.setState({Trainers:snapshot.val().childTrainers},console.log(this.state.Trainers))
但是现在它没有返回任何内容。您在构造函数中绑定了setState函数了吗?并对forEach中的每个函数使用箭头函数also@RagibHuda哎呀。。。