[英]I'm getting an undefined error in my project made with React
I am sending as a prop an array of objects.我正在发送一组对象作为道具。 When I
console.log(this.props)
I get the array of objects, but when I try to assign it to a variable it gives me当我
console.log(this.props)
我得到了对象数组,但是当我尝试将它分配给一个变量时,它给了我
TypeError:ninjas is undefined
类型错误:忍者未定义
This is how i send the prop这就是我发送道具的方式
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;
And this is how i recibe it这就是我的食谱
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 list={ this.state.ninjas }/>
I suggest you change this to我建议你把这个改成
<Ninjas ninjas={ this.state.ninjas }/>
Otherwise the name would be list
in your child component.否则该名称将
list
在您的子组件中。
In other words the name of the property you use when rendering the component (here in the render
function of App
) has to correspond to the name you get from the props
object in your child component (here your child component is Ninjas
).换句话说,您在渲染组件时使用的属性名称(此处为
App
的render
函数)必须与您从子组件中的props
对象获得的名称相对应(此处您的子组件为Ninjas
)。
You are passing ninjas
in your Ninjas component <Ninjas list={ this.state.ninjas }/>
using list props.您正在使用列表道具在 Ninjas 组件
<Ninjas list={ this.state.ninjas }/>
中传递ninjas
。 So, you should be using this const { list } = this.props;
所以,你应该使用这个
const { list } = this.props;
instead of const { ninjas } = this.props;
而不是
const { ninjas } = this.props;
in your Ninjas Component.在你的 Ninjas 组件中。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.