繁体   English   中英

如何从内部使用的异步 function 返回一个值。map function 在 React 中?

[英]How to return a value from async function used inside .map function in React?

所以我用谷歌搜索了一下,我发现异步 function 返回 promise 可以在异步 function 之后通过 using.then() 访问结果值。 这就是它无法正确渲染的原因。 我的问题是:如何从这个 promise inside.map 呈现实际值?

const storageRef = firebase.storage().ref("/assets")

const [productList, setProductList] = useState([])

useEffect(() => {
    Axios.get("http://localhost:3001/product/get").then((response) => {
        setProductList(response.data)
    })  
}, [])

const getImage = async (bannerImage) => {
    const url = await storageRef.child(bannerImage).getDownloadURL();
    return url;   
}

Map function(返回Error: Objects are not valid as a React child (found: [object Promise]) ):

{productList.map((val) => {
    return (
        <div key={val.id} className="product">
            <div className="item">
                <h1>Product title: {val.title}</h1>
                <h2>Price: {val.price}</h2>
                <h2>Quantity: {val.quantity}</h2>
                <h2>IMG: {getImage(val.bannerImage)}</h2>
            </div>
        </div>
    ) 
})}

因此,正如@Chris-G 建议的那样,您可以 map over response.data中的.then链接到Axios.get到 go ,获取您需要的图像 URL 渲染的对象。 例子:

const storageRef = firebase.storage().ref("/assets");
const getImage = async (bannerImage) => {
    const url = await storageRef.child(bannerImage).getDownloadURL();
    return url;   
}

const [productList, setProductList] = useState([])

useEffect(() => {
    Axios.get("http://localhost:3001/product/get").then((response) => {
        Promise.all(response.data.map(async (rawProduct) => {
            const renderReadyProduct = {
                title: rawProduct.title,
                price: rawProduct.price,
                quantity: rawProduct.quantity
            };
            renderReadyProduct.img = await getImage(rawProduct.bannerImage);
            return renderReadyProduct;
        })).then((newProductList) => setProductList(newProductList));
    });
}, [])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM