简体   繁体   中英

How can I accumulate string values ​in useState as an array value in React?

I created a value called degrowth LengthImg with the useState array. When the deleteImgfunc function is executed, the value is entered as a string value. if deleteImgfunc excuted The first may contain a "buger" value, if deleteImgfunc excuted second time "pizza" value may come in.

At this time, I want to store string values in degrowthLengthImg as an array.

like this expected answer

    degrowthLengthImg = ["buger", "pizza"]

so i made my code but it comes out like blow

   degrowthLengthImg = ["b", "g", ....]

this is my code

    const [degrowthLengthImg, setDegrowthLengthImg] = useState([])

    const deleteImgfunc = useCallback((value: string) => {
            setDegrowthLengthImg([...degrowthLengthImg, value]);

    }, []);

 return(
     <Pressable style={farmDiaryViewWrapperStyle.imgcloseBtn}
     onPress={() => 
    deleteImgfunc?.(v?.name)}
    >
      )

How can i fix my code?

Use the following to add value to the array. Do not use the push function to push to an array. Also, the useCallback is unnecessary.

    const [degrowthLengthImg, setDegrowthLengthImg] = useState([])

    const deleteImgfunc = useCallback((value: string) => {
           // If you want to add to array
            setDegrowthLengthImg(deg => [...deg, value]);
    }, []);

You should use setDegrowthLengthImg as,

 setDegrowthLengthImg(degrowthLengthImg => [...degrowthLengthImg, value]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM