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

致庸
  • 3
新手上路,请多包涵

基本情况介绍

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

{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信息

image

element信息

image

疑问

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

回复
阅读 340
1 个回答
✓ 已被采纳
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);
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
你知道吗?

宣传栏