我正在发送一个对象数组作为道具。当我console.log(this.props)
时,我得到了对象数组,但是当我尝试将其分配给变量时,它给了我
TypeError:ninjas未定义
这就是我发送道具的方式
import React from 'react';
import Ninjas from './Ninjas';
class App extends React.Component {
state = {
ninjas:[
{name:"Ryu",age:"20",belt:"black",key:"1"},
{name:"Yoshi",age:"22",belt:"yellow",key:"2"},
{name:"Mario",age:"25",belt:"white",key:"1"}
]
}
render(){
return (
<div>
<h1>My first React App</h1>
<Ninjas list={ this.state.ninjas }/>
</div>
)
}
}
export default App;
这就是我的收录方式
import React from 'react';
class Ninjas extends React.Component {
render(){
const { ninjas } = this.props;
const ninjasList = ninjas.map(ninja => {
return(
<div className="ninja" key={ ninja.key }>
<div>Name: { ninja.name }</div>
<div>Age: { ninja.age }</div>
<div>Belt: { ninja.belt }</div>
</div>
)
})
return (
<div className="ninja-list">
{ ninjasList }
</div>
);
}
}
export default Ninjas;
最佳答案
您正在使用列表道具在忍者组件ninjas
中传递<Ninjas list={ this.state.ninjas }/>
。因此,您应该在忍者组件中使用此const { list } = this.props;
而不是const { ninjas } = this.props;
。
import React from 'react';
class Ninjas extends React.Component {
render(){
const { list } = this.props;
const ninjasList = list.map(ninja => {
return(
<div className="ninja" key={ ninja.key }>
<div>Name: { ninja.name }</div>
<div>Age: { ninja.age }</div>
<div>Belt: { ninja.belt }</div>
</div>
)
})
return (
<div className="ninja-list">
{ ninjasList }
</div>
);
}
}
export default Ninjas;