React : props 未定义,但当我 console.log(props) 时,它可以工作

vin*_*996 1 javascript reactjs react-props

我有一个返回此的箭头函数:

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

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

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>
  );
};
Run Code Online (Sandbox Code Playgroud)

如果我console.log(post),我可以看到我的5个对象,但是如果我取消注释“//const {author, date_creation, message} = post”并将author = {'author "}替换为author = {author} (这是一个道具),它让我“ TypeError: Cannot destruct property 'author 'of 'post '因为它是未定义的。”

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

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'}
Run Code Online (Sandbox Code Playgroud)

小智 6

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

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

或者

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

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

  • 有用 !非常感谢您快速有效的回复!!!! (2认同)