简体   繁体   中英

data returns as undefined on first render

function Story() {
  let { id } = useParams();
  const pin = useSelector(state => state.pins.pin);
  const dispatch = useDispatch();
  const userid = 2
  useEffect(() => {
    dispatch(getPin(id));
  }, [dispatch, id]);

  return (
    <div className="container-fluid" >

     <Upvote pin={pin.upvotes} userid={userid} />

    </div>
  );
}
function Upvote ({pin, userid}) {
  ///pin.filter(a => a.id === userid)
  return <div>test<div/>
}

pin would be undefined at first render. I tried doing an if statement in Upvote. not sure if that is the right way

if(pin)
   ///filter

That is probably because the initial state of pin is undefined, or pin comes from a fetch operation, which is asynchronous.

What you can do is to conditionally render your child Upvote component only if pin is defined.

return (
  <div className="container-fluid" >
    {pin && pin.upvotes && <Upvote pin={pin.upvotes} userid={userid} />}
  </div>
);

You can do something like

{pin && <Upvote pin={pin.upvotes} userid={userid} />}

To only render the component when pin is not undefined. Alternatively you may want to have default values you can use when pin isn't defined and then you can do

<Upvote pin={pin ? pin.upvotes : defaultValue} userid={userid} />

Put a ternary operator in Story before rendering Upvote as if pin is not present, Upvote won't render only.

Also, it will not break your code when pin is undefined.

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.

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