function组件 收到新props, 但是不更新?

基本情况介绍

想要从数据库中获取图片信息列表,如下:

{imgs:

[

{_id: '...',img:'***.png'},

...,

]

}

然后,用ali-oss签名地址,并存储到images状态中

{imgs:

[

{_id:'...', img: '***.png', src: '签名后的地址'}

...,

]

}

传给子列表组件:

<PictureList imgs={images}

子列表组件接受到props,但是不渲染

const PictureList = ({ imgs }) => {

return (

<ul>

{imgs.map((i) => (

<img key={i._id} src={i.src} alt="pic" />

))}

</ul>

);

}

export default PictureList

代码

Picture.js

import React, {useEffect, useState, useRef } from 'react'

import { useAlioss } from '../../hooks/oss-hook'

import PictureList from '../../components/PictureList'

import './style.less'

const Pictures = () => {

const [loading, setLoading] = useState(true)

const [signatured, setSignatured] = useState(false)

const [results, setResults] = useState()

const [images, setImages] = useState([])

const { allowUrl } = useAlioss()

useEffect(() => {

getImages();

}, [])

async function getImages() {

try {

const dbResponse = await fetch(

`${process.env.REACT_APP_BACKEND_URL}/upload/images`

);

const resu = await dbResponse.json();

setResults(resu);

const temImgs = []

await resu.imgs.forEach((result) => {

allowUrl(result.img).then((res) => {

result.src = res;

temImgs.push(result)

});

});

setImages(temImgs);

} catch (e) {

console.log("get images failed")

} finally {

setLoading(false)

console.log("get images and signatured")

}

}

return (

<div className="picture">

{loading ? <h1>Loading</h1> : <PictureList imgs={images} />}

</div>

);

};

export default Pictures

PictureList.js

const PictureList = ({ imgs }) => {

return (

<ul>

{imgs.map((i) => (

<img key={i._id} src={i.src} alt="pic" />

))}

</ul>

);

}

export default PictureList

dev信息

element信息

疑问

是那个地方的问题?
async/await ?
还是function组件我用的不对?
(我已经开始怀疑一切了,甚至npm install了好几遍!)

回答

const tasks = resu.imgs.map((result) => new Promise(allowUrl(result.img)));

Promise.all(tasks).then(values => {

let resultImgs = resu.imgs.map((t,index) => ({...t, src: values[index] }));

setImages(resultImgs);

})

以上是 function组件 收到新props, 但是不更新? 的全部内容, 来源链接: utcz.com/a/42803.html

回到顶部