Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/457.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript TypeError:无法从未定义中读取属性“0”_Javascript_Reactjs - Fatal编程技术网

Javascript TypeError:无法从未定义中读取属性“0”

Javascript TypeError:无法从未定义中读取属性“0”,javascript,reactjs,Javascript,Reactjs,我是ReactJS的初学者,下面是我尝试运行的示例程序: App.js 第行: <Person name={this.state.persons.name[0]} age ={this.state.persons.age[0]}/> 有人能帮上忙吗?这里是数组,而不是: this.state.persons.name[0] 应该是: this.state.persons[0].name 您没有正确引用数组项: this.state.persons.age[0]正如其他答案所指

我是ReactJS的初学者,下面是我尝试运行的示例程序:

App.js

第行:

<Person name={this.state.persons.name[0]} age ={this.state.persons.age[0]}/> 

有人能帮上忙吗?这里是数组,而不是:

this.state.persons.name[0]
应该是:

this.state.persons[0].name

您没有正确引用数组项:


this.state.persons.age[0]正如其他答案所指出的,您正试图访问一个名和年龄为0的属性。但您希望访问数组中的每个项

如果名称和年龄是一个对象,这将起作用

name: {
   "0": 'Bad Name'
}

age: {
   "0": 'Bad Age'
}
但在本例中,它是一个原语字符串和数字 这也可以写在这些行中

<button>Switch </button>
{
  this.state.persons.map(person => {
      // each iteration is the item in the array
      // which is the person in this case
      const {
        age,
        name
      } = person;

      return (
        <Person name={name} age ={age} key={name}/> 
      )
  });
}

首先获取索引,然后获取键this.state.persons[0]。命名为this.state.persons[0]。年龄为this.state.persons[1]。命名为this.state.persons[1]。年龄
this.state.persons[0].name
name: {
   "0": 'Bad Name'
}

age: {
   "0": 'Bad Age'
}
<button>Switch </button>
{
  this.state.persons.map(person => {
      // each iteration is the item in the array
      // which is the person in this case
      const {
        age,
        name
      } = person;

      return (
        <Person name={name} age ={age} key={name}/> 
      )
  });
}