Javascript TypeError:无法从未定义中读取属性“0”
我是ReactJS的初学者,下面是我尝试运行的示例程序: App.js 第行: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]正如其他答案所指
<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}/>
)
});
}