如何解决React Native:状态更新未触发重新渲染
我的RN 0.62.2应用程序上传图像并显示它们。图像存储在状态数组中。当上传新图像时,新图像将添加到数组末尾。这是添加图像的方法:
const [imgs,setImgs] = useState();
const addImages = (pics) => {
if (!pics || pics===[] || pics==={}) return;
let temp = imgs,updated=false;
if (imgs && imgs!==[] && imgs!=={}) {
let names = imgs.map(item => item.fileName);
for(let i=0;i<pics.length;i++) {
if (!names.includes(pics[i].fileName)) {
temp.push(pics[i]);
updated = true;
};
};
if (updated) setImgs(temp); //<<== add more images to the array and reset the state
} else {
setImgs(pics); //<<==for initial upload of images
};
图像数组显示在组件内:
return (
<MyAccordion title={"Image"} absPosition={false} initOpen={accordImgOpen} screenSize={{width:screen_width,height:((imgs && imgs.length>9) ? screen_width+(screen_width/3)*(Math.ceil(((imgs.length-9)%3)/3)):screen_width)}} >
<DisplayImages pics={imgs} deleteImage={deleteImage} /> //<<==here imgs is a state and the images array is display in grids
</MyAccordion>
)
代码一直运行到今天。现在添加的图像之后没有立即由功能组件DisplayImages
呈现。我需要做一些事情,例如打开Modal并关闭它以触发重新渲染。在控制台输出上,显示状态imgs
已更新。什么能阻止页面在状态更新后重新呈现?
解决方法
我认为这里的问题是您尚未克隆img。试试这个
const [imgs,setImgs] = useState();
const addImages = (pics) => {
if (!pics || pics===[] || pics==={}) return;
let temp = [...imgs],updated=false;
if (imgs && imgs!==[] && imgs!=={}) {
let names = imgs.map(item => item.fileName);
for(let i=0;i<pics.length;i++) {
if (!names.includes(pics[i].fileName)) {
temp.push(pics[i]);
updated = true;
};
};
if (updated) setImgs(temp); //<<== add more images to the array and reset the state
} else {
setImgs(pics); //<<==for initial upload of images
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。