简体   繁体   English

React.js:无法在render()函数的对象数组中获取属性

[英]React.js: can't get an property in an array of objects in render() function

how to I get the property of an array of objects in the render function. 如何在render函数中获取对象数组的属性。 if I try this: 如果我尝试这样:

render() {
    console.log(this.state.items[0].name);
 (...)

I got an error: 我收到一个错误:

TypeError: this.state.items[0] is undefined TypeError:this.state.items [0]未定义

  class App extends React.Component {
  constructor() {
    super()

    this.state = {
      items: []
    }
  }
  componentWillMount() {
    fetch('http://swapi.co/api/people/?format=json')
      .then((response) => response.json())
        .then(({ results: items }) => this.setState({ items }))
  }

  filter(e){
    this.setState({ filter: e.target.value })
    console.log(this.state.items[0].name);
  }

  render() {
    console.log(this.state.items[0].name);
    return (
      <div>
        <input type="text" onChange={this.filter.bind(this)}  />
      </div>
    )
  }

}
export default App

However, if I log out only the first element of the array 但是,如果我仅注销数组的第一个元素

 console.log(this.state.items[0])

it prints out the object 它打印出对象

Object { name: "Luke Skywalker", height: "172", mass: "77", hair_color: "blond", skin_color: "fair", eye_color: "blue", birth_year: "19BBY", gender: "male", homeworld: " http://swapi.co/api/planets/1/ ", films: Array[5], 6 more… } 对象{名称:“卢克·天行者”,身高:“ 172”,体重:“ 77”,头发颜色:“金发”,皮肤颜色:“一般”,眼睛颜色:“蓝色”,生日:“ 19BBY”,性别:“男性” ,家庭世界:“ http://swapi.co/api/planets/1/ ”,电影:Array [5],另外6个…}

When the filter function get fired I do get the property of the first element console.log(this.state.items[0].name) 当过滤器功能被触发时,我确实获得了第一个元素console.log(this.state.items [0] .name)的属性。

prints out: 打印出:

Luke Skywalker 卢克·天行者

What's happening here? 这里发生了什么事?

Your state.items array is not set until your fetch has completed. 在获取完成之前,不会设置state.items数组。 Your render method will be called prior to this, therefore, it won't work as expected. 您的render方法将在此之前被调用,因此,它将无法按预期工作。

If you recheck your console output, I have a feeling you'll see some nulls or undefined's prior to the your object showing. 如果您重新检查控制台输出,我感觉您会在显示对象之前看到一些null或undefined。

Try this: 尝试这个:

 render() {
    console.log(this.state.items.length > 0 ? this.state.items[0].name : 'Items not loaded yet');
    return (
      <div>
        <input type="text" onChange={this.filter.bind(this)}  />
      </div>
    )
  }

fetch is asynchronous call, so during first time rendering this.state.items will [] and you are trying to access the name of 0th item that doesn't exist, and it is throwing the error because of that. fetch是异步调用,因此在第一次呈现this.state.items[]并且您尝试访问不存在的第0个项目的name ,因此this.state.itemsthis.state.items错误。

When you are using: 使用时:

console.log(this.state.items);

Check the console it was printing two values one [] and another one will be the data that you are getting from server. 检查控制台,它正在打印两个值一个[] ,另一个将是您从服务器获取的数据。

Solution: 解:

Put the check on length inside render it will print the proper name once you get the response. 将检查的长度放到render内,一旦获得响应,它将打印正确的名称。

Like this: 像这样:

render(){
   if(this.state.items.length)
       console.log(this.state.items[0].name);

   return(
       ....
   )
}

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

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