简体   繁体   English

如何访问嵌套在 React 中的状态数组中的对象中的元素?

[英]How to access elements in an Object which nested in an array of State in React?

I'm learning React, and today I encountered a problem.正在学习React,今天遇到一个问题。 I tried to fetch data from an api, everything went well untill I changed the 'character' from an object to an array.我试图从 api 获取数据,一切都很顺利,直到我将“字符”从对象更改为数组。 After it, my jsx no longer could access elements from the state.之后,我的 jsx 无法再访问 state 中的元素。

The snippet of the original code is as follow:原始代码片段如下:

//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>
        )
    }

}

Later, I wanted to imporve the data structure, so I changed the 'character' state to an Array, according which I changed the way to access the 'character', turned out it's no longer works.后来,我想改进数据结构,所以我将'字符'状态更改为数组,根据该数组更改了访问'字符'的方式,结果它不再有效。

// 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>
        )
    }

}

I don't know how to fix this.我不知道如何解决这个问题。

It worked with an object because you tried to access a property that doesn't exist on the object and got undefined instead它与一个对象一起工作,因为您试图访问该对象上不存在的属性,而是undefined

When you try to access the data before the http request finishes, array[0] is undefined and will throw an error when you try to access a property on undefined当您尝试在 http 请求完成之前访问数据时, array[0] undefined并且当您尝试访问undefined上的属性时会抛出错误

There are a couple of ways you can make it work, when using arrays you can just map over the array and render the elements, if the array is empty nothing will be rendered有几种方法可以让它工作,当使用数组时,你可以映射数组并渲染元素,如果数组为空,则不会渲染任何元素

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

You can also check if there is an element inside the array before trying to access a property on the element if you only want to render the first element如果您只想呈现第一个元素,您还可以在尝试访问元素上的属性之前检查数组中是否有元素

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

But, it looks like you are storing a single character inside the array and it will make sense to just keep it as an object, use arrays when you need to store multiple items instead of just one但是,看起来您正在数组中存储单个字符,将其作为对象保留是有意义的,当您需要存储多个项目而不是一个项目时使用数组

For updating the state based on the previous state, you should use a function instead of an object:要根据先前的状态更新状态,您应该使用函数而不是对象:

this.setState(state => (
  {
    character: state.character.concat(data),
    loading: false
  }
), () => {
  console.log(this.state);
});

Note that react state updates may be asynchronous, that's why I added a callback to my example for tracing the new state.请注意,react 状态更新可能是异步的,这就是为什么我在示例中添加了一个回调来跟踪新状态。

You can read more about React state and lifecycle in the official documentation: https://reactjs.org/docs/state-and-lifecycle.html#using-state-correctly您可以在官方文档中阅读有关 React 状态和生命周期的更多信息: https : //reactjs.org/docs/state-and-lifecycle.html#using-state-correctly

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM