好吧,在我的第二个 useEffect 中,我尝试将 imgFiles 的值传递给 listImg,但我的代码不会立即更新,并且列表为空,即使我在 imgFiles 中有一个值,导致错误“失败”在“URL”中执行“createObjectURL”:重载解析失败。 ” 有谁知道我可以做什么来避免这种情况?
useEffect(() => {
if (listFunc.length !== 0) {
let urls
const imgfetch = async () => {
const imgFiles = await Promise.all(
listFunc.map(async (fun) => {
console.log('funcionarios:',listFunc)
console.log(`${fun.nome} codigo ${fun.cod}`)
let resp = await fetch(url + `imagem/${fun.cod}-func`, { method: 'GET' })
let resposta = await resp.blob()
return resposta
}))
setListImg(imgFiles)//doesn't put the value inside listImg
}
imgfetch();
setStatus('ocioso')
}
}, [listFunc])
...
return (
<div>
{listFunc.map((fun) => {
const url =URL.createObjectURL(listImg[fun.cod-1])//where the error happens
return (
<div style={{ textAlign: "justify", padding: '20px 100px 0px 100px' }} key={fun.cod}>
<div style={{ display: "flex" }}>
<img src={url}></img>
<div style={{ paddingLeft: '20px' }}>
<h2>{fun['nome']}</h2>
<p>{fun.desc}</p><br />
<br />
</div>
{/*user.nome!==''?<button style={{height:'30px',margin:'50px'}}>algo</button>:null*/}
</div>
<hr></hr>
</div>
)
})}
{/*user.nome!==''?<button>algo2</button>:null*/}
</div>
);
我尝试了上面的代码,但 listImg 继续为空 [],即使 imgFiles 具有 blob 值。
您的代码存在一些问题
为了在 Promise.all 之前使用它,映射所有函数并返回 fetch 调用或块取决于你喜欢什么(没有等待),然后将返回值(promise 数组)传递给 Promise.all 然后正常工作异步函数(等待 Promise.all 后)