Since you are passing in a reference as a callback function through your navigation params, you are possibly encountering a stale closure around obj
within addItem
. In otherwords, everytime you call that function, obj will be an empty array, as you initially defined it.
also noticed your initial state and addItem do not match up in terms of json structure. I will assume you want only an array with items (your initial state is an object which contains an array of items)
const[obj,setObj] = useState([])
Try using a callback function within the addItem function in order to get the latest state when calling addItem, in order to spread the correctly populated array.
addItem(item:any) => {
setObj(prevObjState => [...prevObjState, item])
}
if you want an object which contains an array
const [item, addItem] = React.useState({arr:[]});
const addAnotherItem = (item) => {
addItem(prevState => ({...prevState, arr: [...prevState.arr, item] }))
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…