我有以下代码:
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 调用中会及时完成,然后成功地将数据作为 prop 传递给子组件。但是,有时,api 调用未完成,这意味着 ivr_dests 没有与我的子组件相冲突的值。无论如何,我可以在启动 storycarouselitem 之前填充 ivrDests 吗?
谢谢
答案 0 :(得分:0)
这应该有效:
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/),然后使用加载标志。