![](/img/trans.png)
[英]Undefined is not an object evaluating route.params.input. ERROR when passing data between components. REACT NATIVE
[英]React Native Error: undefined is not an object when passing data to component
使用道具将数据传递给我的组件并尝试从那里访问它时出现错误。 我有以下格式的数据
export const data = [
{
id: 0,
title: 'Test',
price: 1500,
},
];
我导入它并通过 props 这样传递数据:
const post0 = data[0];
...
<Post post={post0}/>
在我的组件中,我成功接收到数据,我可以通过类似console.log(props);
的日志进行验证。 并获得以下日志条目
{"post": {"id": "0", "price": "1500", "title": "Test"}}
当我现在尝试访问组件中的某个属性时,例如 id
<Text> { props.post.id } </Text>
我收到错误“TypeError: undefined is not an object (evalating 'props.post.title')”
如何使用组件中的数据? 我假设我必须以某种方式 map 数据但无法解决它。
您的组件是基于 class 的组件还是功能组件? 如果它是基于 class 的组件,您应该使用“this”关键字访问您的道具。 例如
export class Post extends React.Component {
render() {
return (
<View>
<Text>{this.props.post.id}</Text>
<Text>{this.props.post.title}</Text>
</View>
)
}
}
如果是功能组件,可以直接访问props。 例如:
export function Post(props) {
return (
<View>
<Text>{props.post.id}</Text>
<Text>{props.post.title}</Text>
</View>
)
}
我自己发现了问题。 我第二次在我的代码中使用了 post 组件,没有任何道具,因此它确实是未定义的。 当始终将 object 传递给组件时,获取像 {post.id} 这样的 object 属性非常有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.