简体   繁体   English

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

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

So I googled a bit and I found that async function return promise which result value can be accessed by using.then() after this async function.所以我用谷歌搜索了一下,我发现异步 function 返回 promise 可以在异步 function 之后通过 using.then() 访问结果值。 That is why it can't render properly.这就是它无法正确渲染的原因。 My question is: how can I render an actual value from this promise inside.map?我的问题是:如何从这个 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 (returns Error: Objects are not valid as a React child (found: [object Promise]) ): 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>
    ) 
})}

So, as @Chris-G suggested, you could map over response.data in the .then chained on Axios.get to go ahead, get the image URLs, and construct the objects that you'll need for the render.因此,正如@Chris-G 建议的那样,您可以 map over response.data中的.then链接到Axios.get到 go ,获取您需要的图像 URL 渲染的对象。 Example:例子:

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