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

时间:2020-10-18 00:24:06

标签: javascript reactjs react-props

我是React Noobie或Midbie。该组件正在映射来自其父级的空posts数组作为道具。

我如何让它等到道具完成更新后再执行映射发生的return()

我认为我需要使用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;

1 个答案:

答案 0 :(得分:4)

如果尚未填充数组,还可以使用内联条件来防止映射。

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