第二次访问屏幕时,React Native null不是对象(正在评估"_this2.state.data")错误 [英] React Native null is not an object (evaluating'_this2.state.data') error when visiting the screen a second time

查看:78
本文介绍了第二次访问屏幕时,React Native null不是对象(正在评估"_this2.state.data")错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码成功呈现我的Firebase数据库查询.

I'm using the following code to successfully render my Firebase database query.

class WeightHistoryScreen extends Component {
componentWillMount = () => {
    this.setState({ data: [] });
    this.getData();
  }

  getData(){
    const { currentUser } = firebase.auth();
    firebase
      .database()
      .ref(`/users/${currentUser.uid}/data/`)
      .orderByKey()
      .on('child_added', snap =>  {
        var data = this.state.data;
        data.push({ key: snap.key, weight: snap.val().Weight });
        this.setState({ data: data });
      }) 
  }

renderRow = ({item}) => {
  return (
    <View style={[styles.card, styles.cardBorder]}>
      <Text>
        {item.key}
      </Text>
      <Text style={[styles.textRight]}>
        {item.weight} LBS
      </Text>
    </View>
  )
}

  render() {
    return (
      <View style={[styles.container]}>
        <FlatList
          data={this.state.data}
          renderItem={this.renderRow} 
        />
      </View>
    );
  }
}

但是,在同一会话中第二次访问屏幕时出现错误.请参见下面的屏幕截图.

However I'm getting an error when visiting the screen a second time on the same session. See the screenshot below.

推荐答案

您正在错误的位置初始化状态,请尝试通过这种方式进行操作

You are initializing your state in the wrong place, try to do it this way

class WeightHistoryScreen extends Component {
state={data:[]}
componentWillMount = () => {
    this.getData();
  }

这篇关于第二次访问屏幕时,React Native null不是对象(正在评估"_this2.state.data")错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆