[英]React Native Error: undefined is not an object when passing data to component
I am getting an error when passing data to my component with props and trying to access it from there.使用道具将数据传递给我的组件并尝试从那里访问它时出现错误。 I have my data in the following format
我有以下格式的数据
export const data = [
{
id: 0,
title: 'Test',
price: 1500,
},
];
I import it and pass the data like via props this:我导入它并通过 props 这样传递数据:
const post0 = data[0];
...
<Post post={post0}/>
In my component I receive the data succesfully which I can verify via log like this console.log(props);
在我的组件中,我成功接收到数据,我可以通过类似
console.log(props);
的日志进行验证。 and get the following log entry并获得以下日志条目
{"post": {"id": "0", "price": "1500", "title": "Test"}}
When I now try to access a certain property like id in my component当我现在尝试访问组件中的某个属性时,例如 id
<Text> { props.post.id } </Text>
I get the error 'TypeError: undefined is not an object (evaluating 'props.post.title')'我收到错误“TypeError: undefined is not an object (evalating 'props.post.title')”
How can I use the data in my component?如何使用组件中的数据? I am assuming I somehow have to map the data but couldn't resolve it.
我假设我必须以某种方式 map 数据但无法解决它。
Is your component a class based component or a functional component?您的组件是基于 class 的组件还是功能组件? If it is a class based component, you should access your props using "this" keyword.
如果它是基于 class 的组件,您应该使用“this”关键字访问您的道具。 For example
例如
export class Post extends React.Component {
render() {
return (
<View>
<Text>{this.props.post.id}</Text>
<Text>{this.props.post.title}</Text>
</View>
)
}
}
If it is a functional component, you can access the props directly.如果是功能组件,可以直接访问props。 For example:
例如:
export function Post(props) {
return (
<View>
<Text>{props.post.id}</Text>
<Text>{props.post.title}</Text>
</View>
)
}
I found the problem myself.我自己发现了问题。 I used the post component in my code a second time without any props so therefore it was indeed undefined.
我第二次在我的代码中使用了 post 组件,没有任何道具,因此它确实是未定义的。 Getting the object properties like {post.id} works perfectly fine when always having an object handed to the component.
当始终将 object 传递给组件时,获取像 {post.id} 这样的 object 属性非常有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.