【问题标题】:ensuring that axios api call finishes for props before rendering child component确保在渲染子组件之前完成对道具的 axios api 调用
【发布时间】:2021-09-30 00:20:10
【问题描述】:

我有以下代码:

function StoryCarousel(props) {
    const [ivrDests, setIVRDests] = useState([]);

    useEffect(() => {
        async function getIVRDests() {
          var data = {
            "customer-id": customer_id
          };
          let response = await axios.post(`http://localhost:2000/files/get-ivr-dests`, data)
          //let response = await axios.post(`/files/get-files`, data)
          setIVRDests(response.data)
        }
        getIVRDests() 
        
    }, []);

  return (
    <div className="StoryCarousel">
        <StoryCarouselItem ivr_dests={ivrDests} options={props.options} />
    </div>
  );
}

此代码有时会起作用,因为 api 调用会及时完成,然后成功地将数据作为道具传递给子组件。但是,有时,api 调用没有完成,这意味着 ivr_dests 没有与我的子组件相关的值。无论如何我可以做到,以便在启动故事轮播之前必须填充 ivrDests?

谢谢

【问题讨论】:

    标签: javascript reactjs react-redux react-hooks use-effect


    【解决方案1】:

    这应该可行:

    function StoryCarousel(props) {
        const [ivrDests, setIVRDests] = useState([]);
    
        useEffect(() => {
            async function getIVRDests() {
              var data = {
                "customer-id": customer_id
              };
              let response = await axios.post(`http://localhost:2000/files/get-ivr-dests`, data)
              //let response = await axios.post(`/files/get-files`, data)
              setIVRDests(response.data)
            }
            getIVRDests() 
            
        }, []);
    
      return (
        <div className="StoryCarousel">
            {ivrDests.length != 0 && <StoryCarouselItem ivr_dests={ivrDests} options={props.options} />}
        </div>
      );
    }
    

    您还可以使用自定义挂钩(或获取提供该挂钩的库,例如 https://react-query.tanstack.com/),然后使用加载标志。

    【讨论】:

      猜你喜欢
      • 2021-01-06
      • 1970-01-01
      • 2021-05-18
      • 2018-09-19
      • 2023-04-01
      • 2018-11-08
      • 2021-10-01
      • 1970-01-01
      • 2022-12-03
      相关资源
      最近更新 更多