首页 > 解决方案 > 如何访问嵌套在 React 状态数组中的对象中的元素?

问题描述

我正在学习React,今天遇到了一个问题。我试图从 api 获取数据,一切都很顺利,直到我将“字符”从对象更改为数组。之后,我的 jsx 不再可以访问状态中的元素。

原代码片段如下:

//When the state 'character' is an object

class Api extends React.Component {
    state = {
        loading: false,
        character: {}
    }

    componentDidMount() {
        this.setState({ loading: true });
        fetch('https://swapi.co/api/people/1')
            .then(response => response.json())
            .then(data => {
                this.setState(
                    {
                        character: data,
                        loading: false
                    }
                );
                console.log('newstate', this.state.character);
            });
    }
    render() {
        return (
    <div><h3>Name: {this.state.character.name}</h3>
            </div>
        )
    }

}

后来我想改进数据结构,所以我把'character'状态改成了一个Array,据此我改变了访问'character'的方式,结果它不再起作用了。

// after I changed the type of 'character'

class Api extends React.Component {
    state = {
        loading: false,
        character: []
    }

    componentDidMount() {
        this.setState({ loading: true });
        fetch('https://swapi.co/api/people/1')
            .then(response => response.json())
            .then(data => {
                this.setState(
                    {
                        character: this.state.character.concat(data),
                        loading: false
                    }
                );
                console.log('newstate', this.state.character);
            });
    }
    render() {
        return (
    <div><h3>Name: {this.state.character[0].name}</h3>
            </div>
        )
    }

}

我不知道如何解决这个问题。

标签: javascriptreactjs

解决方案


它与对象一起工作,因为您尝试访问对象上不存在的属性,undefined而是得到了

当您尝试在 http 请求完成之前访问数据时,当您尝试访问属性array[0]undefined会抛出错误undefined

有几种方法可以使它工作,当使用数组时,您可以映射数组并渲染元素,如果数组为空,则不会渲染任何内容

<div>
  {this.state.character.map(char => (
    <h3 key={char.name}>Name: {char.name}</h3> // don't forget the key
  )}
</div>

如果您只想呈现第一个元素,您还可以在尝试访问元素上的属性之前检查数组中是否有元素

<div>
  {this.state.character[0] && (
    <h3>Name: {this.state.character[0].name}</h3>
  )}
</div>

但是,看起来您在数组中存储了一个字符,将其保留为一个对象是有意义的,当您需要存储多个项目而不是一个项目时使用数组


推荐阅读