0

state variable is here

const add = useSelector((state)=>state.add);

const [addImgTag,setAddImgTag] = useState([]); //Tags to be rendered on screen
const [addImgs,setAddImgs] = useState([]); 

addImgTag is first modified by useEffect. When the global state variable add changes, addImgTag changes.

useEffect(() => {
        if (add != null && add.imgArr != null) {
          setAddImgSize(add.imgArr.length);
      
          const tags = add.imgArr.map((item, index) => (
            <div className={style.addThumb} key={"add" + index}>
              <img src={item.trim()} alt="광고이미지" />
              <button
                type="button"
                className={style.delAddImg}
                onClick={(e) => {
                  delImg(e, index);
                }}
              >
                x
              </button>
              <input type="hidden" name="addImg" defaultValue={item} />
            </div>
          ));
      
          setAddImgTag(tags);
},[add])

And when the user adds an image from the screen, the preview tag is added to addImgTag.

const addAddImgBox = (event)=>{
        var reader = new FileReader();
        reader.readAsDataURL(event.target.files[0]);
        
        setAddImgs([...addImgs,{"name":"addImgs","files":event.target.files}]);
        reader.onload = function(e){
            let tag =<div className={style.addThumb} key={"addImg"+addImgSize}>
                <img src={e.target.result}/>
                <button type="button" className={style.delAddImg} onClick={(e)=>{delImg(e,addImgSize)}}>x</button>

            </div>;
            setAddImgTag([...addImgTag,tag]);
            setAddImgSize(addImgSize+1);
            
        }
    }

Finally, the image deletion event handler.

const delImg = (e,index)=>{
                        console.log(addImgTag);//No element entered last
            const tempTag = addImgTag.map((item,i)=>{
                if(i==index){
                    return <></>;
                }else{
                    return item;
                }
            })
            console.log(tempTag)
            setAddImgTag(tempTag)

It seems that the last input element was not added to addImgTag at the time the event handler was executed, but it came out well on the screen, so I don't know how to fix it. help

I fixed the add variable as a redux global variable. But I don't know how to do addImgTag

  • https://stackoverflow.com/questions/71447566/react-state-variables-not-updating-in-function this is answer! – 홍유진 Aug 07 '23 at 09:27
  • Does this answer your question? [React State Variables Not Updating in Function](https://stackoverflow.com/questions/71447566/react-state-variables-not-updating-in-function) – Harsh Patel Aug 08 '23 at 11:12

0 Answers0