I'm a React noobie, or midbie. This component is mappping an empty posts
array coming as a prop from its parent.
How do I make it wait until the props having finished updating before doing the return()
where the mapping happens?
I think I need to use useEffect
but I'm not sure the syntax.
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} />
))}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.