【问题标题】:null is not an object evaluating this.state.<name>null 不是评估 this.state.<name> 的对象
【发布时间】:2018-08-24 16:00:21
【问题描述】:

这个问题可能很常见,但我之所以问是因为我无法解决它。我在第 22 行得到“null 不是对象(评估 'this.state.albums')

而且我有点不清楚调用后返回的数据类型以及如何处理它。拜托,有人可以帮我解释一下吗?我正处于学习阶段。当我直接提醒 response.data 我得到 [object][object] 我必须执行 JSON stringify 才能查看数据。我们为什么要这样做?

   import React, { Component } from 'react';
   import {Text} from 'react-native';
   import axios from 'axios';

   export default class AlbumList extends Component{
        constructor(props) {
        super(props);
        state = { albums : []};
        }

   componentWillMount(){
    console.log('in componentWillMount');
    //debugger;
    //alert("first"+this.state);
    axios.get('https://rallycoding.herokuapp.com/api/music_albums')
    .then((response) => {
        //console.log(response);
        //alert(JSON.stringify(response));
        this.setState({albums : response.data});
        //alert(JSON.stringify(this.state.albums));
    })
    .catch((error) => {
        alert(error);
    });
}

renderAlbums(){
    return this.state.albums.map( album => <Text>{album.title}</Text>); //line 22
}

 componentDidMount() {
console.log('I was triggered during componentDidMount')
 }

render(){
    return(
        <Text>{this.renderAlbums()}</Text>
        //<Text>Hiii</Text>
    );
}
}

【问题讨论】:

    标签: json react-native axios


    【解决方案1】:

    您的构造函数中缺少this

    constructor(props) {
       super(props);
       this.state = { albums : []};
    }
    

    至于警报,您不能提醒对象它必须是一个字符串。所以提醒JSON 对象就是[object object]。如果您使用JSON.stringify,它会将对象转换为可用于警报的字符串。在您的console 中,您可以很好地记录对象,并且它们的结构更具可读性。我会坚持使用console.log 进行调试。

    【讨论】:

    • 谢谢!!解决了。我向您介绍了 JSON,您能否解释一下我们在整个组件构建中使用的“this”背后的故事。
    • 找了几个小时,你救了我的命!
    • 你好,我有 TypeError: null is not an object (evalating '_this.state.tags.map') 问题,因为我的标签在第一次任何解决方案时都是空的
    猜你喜欢
    • 1970-01-01
    • 2017-04-08
    • 2022-01-05
    • 2021-10-20
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    相关资源
    最近更新 更多