React Native:状态更新未触发重新渲染

时间:2020-08-12 06:36:58

标签: react-native react-hooks

我的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已更新。什么能阻止页面在状态更新后重新呈现?

1 个答案:

答案 0 :(得分:1)

我认为这里的问题是您尚未克隆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
    };