简体   繁体   English

在道具准备好之前阻止 React 组件渲染

[英]Prevent React component from rendering before props ready

I'm a React noobie, or midbie.我是 React noobie 或 midbie。 This component is mappping an empty posts array coming as a prop from its parent.该组件正在映射一个空的posts数组,作为来自其父级的道具。

How do I make it wait until the props having finished updating before doing the return() where the mapping happens?在执行映射发生的return()之前,如何让它等到道具完成更新?

I think I need to use useEffect but I'm not sure the syntax.我想我需要使用useEffect但我不确定语法。

const Timeline = props => {
  console.log(props.posts.length); // logs twice: initially 0, then 6 a microsecond later.

  useEffefct(()=>{
    // if props is all done and ready, goto return statement
  }, [props]);

  return (
    <>
      <CreatePost />
      <div className="post-list">
        {props.posts.map((post, i) => ( // this maps the initial empty array
          <Post key={i} post={post} />
        ))}
      </div>
    </>
  );
};

export default Timeline;

You can also use an inline condition to prevent mapping if array is not filled yet.如果数组尚未填充,您还可以使用内联条件来防止映射。

{(props.posts.length > 0) && props.posts.map((post, i) => (
   <Post key={i} post={post} />
))}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM