React:道具未定义但是当我console.log(道具)时,它有效

React : props are undefined but when i console.log(props), it works

我有一个箭头函数 returns 这个:

  return (
    <div className="posts">
      <Post />
      {dataApi.map((post) => {
        return <Post post={post} key={uuidv4()} />;
      })}
    </div>
  );
};

在我的 Post 组件中,我尝试导入作者、日期和 props 中传递的文本,但它告诉我此数据未定义。但是,当我 console.log (post) 时,我的数据出现了……这里是代码:

const Post = ({post}) => {
  //const {author, date_creation, message} = post
  return (
    <div className="post">
      <div className="post__author_group">
        <Avatar className={"post__avatar"} />
        <div className="post__author_and_date">
          <Author className="post__author" author={'author'} />
          <Date className="post__date" date={'date_creation'} />
        </div>
      </div>
      <Text message={'message'} />
      {/* <Media /> */}
      <Interactions />
    </div>
  );
};

如果我 console.log(post),我可以看到我的 5 个对象,但是如果我取消注释 "//const {author, date_creation, message} = post" 并替换 author = {'author "} with author = {author} (which is a prop), it puts me" TypeError: Cannot destructure property' author 'of' post '因为它是未定义的。"

我不知道它是否相关但是当我 console.log (post) 在我的控制台中有我的对象之前,我有两个“未定义”但我不知道它来自哪里。我的控制台:

Post.js: 12 undefined
Post.js: 12 undefined
Post.js: 12 {id: 1, message: 'Hello World', date_creation: '2020-11-11T10: 11: 11.000Z', author: 'Vincent'}
Post.js: 12 {id: 2, message: 'Hello World', date_creation: '2020-11-11T10: 11: 11.000Z', author: 'Vincent'}
Post.js: 12 {id: 3, message: 'Hello World', date_creation: '2017-06-29T15: 54: 04.000Z', author: 'Vincent'}
Post.js: 12 {id: 4, message: 'Hello World', date_creation: '2021-09-03T13: 50: 33.000Z', author: 'Vincent'}
Post.js: 12 {id: 5, message: 'Hello World', date_creation: '2021-09-03T13: 50: 49.000Z', author: 'Vincent'}

这是因为你的组件第一次加载时没有加载你的数据。试试这个:

const Post = ({post}) => {
if(post){
 const {author, date_creation, message} = post // You can destructure here 
 return (
    // ....
  );
}
else return null;
};

如果您收到所有数据,请加载上述组件

 return (
    <div className="posts">
      <Post />
      {dataApi && dataApi.length > 0 && dataApi.map((post) => {
        return <Post post={post} key={uuidv4()} />;
      })}
    </div>
  );