Reactjs 反应组件不反射道具
我有一个函数组件,它将数组作为,将该数组的setState funct作为道具 当组件挂载时,它获取文件并设置状态。状态设置成功,我在dev工具中看到过 当组件出现在我的屏幕上时,在DevTools中我看到道具也被设置为它们应该是什么,但是我的JSX中的.map()没有返回任何内容,即使数组中有项目 代码: 父组件:Reactjs 反应组件不反射道具,reactjs,state,rendering,Reactjs,State,Rendering,我有一个函数组件,它将数组作为,将该数组的setState funct作为道具 当组件挂载时,它获取文件并设置状态。状态设置成功,我在dev工具中看到过 当组件出现在我的屏幕上时,在DevTools中我看到道具也被设置为它们应该是什么,但是我的JSX中的.map()没有返回任何内容,即使数组中有项目 代码: 父组件: const [postFiles, setPostFiles] = useState([]); 子组件:(Dropzone挂钩) 道具:post(具有获取图像的url)、post
const [postFiles, setPostFiles] = useState([]);
子组件:(Dropzone挂钩)
道具:post(具有获取图像的url)、postFiles、setPostFiles
useEffect(() => {
if (post) {
let oldImages = []
post.images.forEach((image) => {
axios.get(image.image).then(res => {
let blob = new Blob([res.data], {type:'image/png'});
blob.lastModifiedDate = new Date();
let file = new File([blob], getImageName(image.image),
{type:'image/png'});
file.preview = image.image;
oldImages.push(file);
})
})
setFiles(oldImages);
}
}, [post])
我的JSX中呈现了这个常量:
const thumbs = files.map(file => (
<div className="thumb" key={uuidv4()}>
<div className="thumb-inner">
<a onClick={() => removeFile(file)} className="remove-image">
<i className="fal fa-times-circle"></i>
</a>
<img src={file.preview} />
</div>
</div>
));
const thumbs=files.map(file=>(
removeFile(file)}className=“remove image”>
));
即使文件状态已成功更改,它也不会反映在我渲染{thumbs}的组件中,直到我单击组件中的其他内容时才会出现。以下操作可能会起作用,因为axios.get是异步的,所以您正在尝试在设置旧图像之前访问它:
Promise.all(
post.images.map((image) =>
axios.get(image.image).then((res) => {
let blob = new Blob([res.data], {
type: 'image/png',
});
blob.lastModifiedDate = new Date();
let file = new File(
[blob],
getImageName(image.image),
{ type: 'image/png' }
);
file.preview = image.image;
return file;
})
)
).then((images) => setFiles(images));
非常感谢,这很有效,但我不明白为什么?oldImages不是在axios.get()之前初始化的吗called@VikhyatDevireddyaxios get返回一个so
oldImages.push(文件)代码>将在设置文件(旧图像)之后执行代码>明白了!非常感谢。