由于某些原因,当我使用此方法从loading
API获取时,状态不会改变。
如何显示“装载.”当电话在运行的时候。
const [product, setProduct] = useState({});
const [loading, setLoading] = useState(false);
const productId = 1;
const fetchProduct = () => {
setLoading(true);
//here commerce is my api, so i fetched the product details and set it to the product state
commerce.products.retrieve(productId).then(data => setProduct(data));
setLoading(false);
}
useEffect(() => {
fetchProduct();
})
if (loading) {
return (
<span>Loading...</span>
)
}
return (
<h1>{product.name}</h1>
)
发布于 2021-06-22 15:22:53
在回收产品之后,您必须在承诺结果中设置完整的状态。
const fetchProduct = () => {
setLoading(true);
commerce.products.retrieve(productId)
.then(data => {
setProduct(data)
//HERE
setLoading(false);
});
}
发布于 2021-06-22 15:25:19
我认为有两种方法可以与您的代码相对应。
首先,这个:
const [isLoading, setIsLoading] = useState(false);
const handleFetch = () => {
setIsLoading(true);
someApiCall().then((r) => {
setIsLoading(false);
});
};
或
const [isLoading, setIsLoading] = useState(false);
const handleFetch = async () => {
setIsLoading(true);
await someApiCall();
setIsLoading(false);
};
发布于 2021-06-22 15:22:26
忘记loading
吧。
您可以从product
的值推断数据是否正在加载。
const Component = () => {
const [product, setProduct] = useState(null);
useEffect(() => {
const getProducts = async () => {
const data = await commerce.products.retrieve(productId)
setProduct(data);
};
getProducts();
}, []);
if (product === null) {
return <span>Loading...</span>;
}
return <h1>{product.name}</h1>;
}
如果您真的想使用一个单独的加载变量,那么您将让它默认到true
,并在给product
赋值的同时将它设置为false
。
https://stackoverflow.com/questions/68086283
复制相似问题