我尝试在componentDidMount的for循环中使用setState更新状态,但是每次出现此错误“无法读取null的'setState'属性”
import React, {Component} from 'react';
import '../../../Config'
import * as firebase from 'firebase';
import './Header.scss'
class MessageBox extends Component {
constructor(props){
super(props);
this.state = {
users:[],
}
this.setState= this.setState.bind(this)
}
componentDidMount(){
firebase.database()
.ref("Users")
.on('value', gotData , errData);
function gotData (data) {
var users = data.val();
console.log(users ,"uuuuuuuuuuuu")
var keys=Object.keys(users);
console.log(keys,"keys")
for (var i = 0; i<keys.length; i++){
var k = keys[i];
var myuser = (users[k]);
this.setState({users: myuser});
console.log(myuser,'newUser')
console.log(myuser.username,"myuserName")
console.log(myuser.id,"myuserId")
console.log(myuser.imageURL,"myuserImage")
答案 0 :(得分:0)
代替
Suitcase current_suitcase, best_suitcase;
使用此
function gotData (data) {
如在react'this'中使用旧语法定义的cur函数一样,您也可以像在构造函数中一样绑定gotData
gotData=()=>{//your code;
}
答案 1 :(得分:0)
1)将this.setState(...)
放在firebase.database()
之外,但要放在componentDidMount(){...}
里面
2)如果您要存储所有 myuser
,请列出所有我的用户并将其放入setState,就像这样 this.setState({ users: listOfMyUser})
希望它将解决您的问题