等待 useEffect 更新状态以传递道具?

时间:2020-12-31 02:55:25

标签: reactjs

我有一个从 api 获取数据的父组件,我想在渲染时获取它一次并将其设置为 state 并将其作为道具传递给一个子组件,然后该子组件将映射到该状态。如何在子组件呈现之前等待“出价”有项目?我认为通过传递 setBids 它会等到出价设置,但我得到了一个空数组来映射


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;

2 个答案:

答案 0 :(得分:0)

您可以在渲染子项之前等待填充 bids

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

答案 1 :(得分:0)

你不能“等待”,不是真的。如果您更多地考虑我应该在“何时”渲染孩子,它可能会有所帮助。

function Parent () {

  const [bids, setBids] = useState(null); // <-- change to null to indicate unset

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

    fetchBids();
  }, [ setBids ]);

  return bids ? <Child bids={bids}/> : null;

}

export default Parent;