Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

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

image

element信息

image

疑问

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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);
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...