英文:
React - undefined properties of object after destructuring
问题
以下是翻译好的代码部分:
我正在尝试在获取数据后呈现对象列表,我能够获取所有数据,但在呈现时,属性为undefined。我做错了什么?以下是我的代码。
import React from 'react';
const Post = (post) => {
const { id, userId, title, body } = post;
console.log(post); // 正常
console.log(post.title); // 未定义
return (
<li key={post.id}>
<div>{title}</div>
<div>{body}</div>
</li>
);
};
export default Post;
希望这对你有所帮助。
英文:
I am trying to render a list of objects after a fetch, I get all the data, but at render time, properties are undefined. What am I doing wrong? Here is my code.
import React from 'react';
const Post = (post) => {
const {id, userId, title, body} = post;
console.log(post); // good
console.log(post.title); // undefined
return (
<li key={post.id}>
<div>{title}</div>
<div>{body}</div>
</li>
);
};
export default Post;
答案1
得分: 4
你忘记了解构传入的 props:
import React from 'react';
const Post = ({ post }) => { // 这里
const { id, userId, title, body } = post;
console.log(post); // 好的
console.log(post.title); // 未定义
return (
<li key={post.id}>
<div>{title}</div>
<div>{body}</div>
</li>
);
};
export default Post;
请记住,使用以下方式:
<Post post={...} />
等同于这样:
Post({ post: { ... } });
英文:
You forgot to destructure the incoming props as well:
import React from 'react';
const Post = ({ post }) => { // here
const { id, userId, title, body } = post;
console.log(post); // good
console.log(post.title); // undefined
return (
<li key={post.id}>
<div>{title}</div>
<div>{body}</div>
</li>
);
};
export default Post;
Remember that using something like this:
<Post post={...} />
is like this:
Post({ post: { ... } });
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论