Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

reactjs - wait for useEffect to update state in order to pass down props?

I have a parent component that is fetching data from an api, I would like to fetch it once on render and set it to state and pass it down as props to a child component that will then map over this state. How can I wait for 'bids' to have items before the child component renders? I thought by passing setBids it would wait until bids is set, but instead im getting an empty array to map over


function Parent () {

const [bids, setBids] = useState([]);

  useEffect(() => {
    const fetchBids = async () => {
      const result = await api.GetBids();
      setBids(result.body);
    
    };

    fetchBids();
}, [ setBids ]);

return ( <Child bids={bids}/>)

}

export default Parent;
function Child(props) {

  const { bids, id } = props;
 
  return (
    <Fragment>
      
      {bids.map((responseBidId) => {
          if (responseBidId === id) {
          return (
            <button onClick={handleView}>view</button>
          );
        } else {
          return (
            <Button
              onClick={handleUpload}
            >
              Upload
            </Button>
          );
        }
      })}
    </Fragment>
  );
}

export default Child;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could wait for bids to be populated before rendering the child:

const [bids, setBids] = useState();
return bids ? <Child bids={bids}/> : null;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...