You would want to use the callback function and get the last state, like so
const update = (categoryName, element) =>
setItems((oldItems) => ({
...oldItems,
[categoryName]: [...(oldItems[categoryName] || []), element]
}));
Full example
import { useEffect, useState } from "react";
export default function App() {
const [items, setItems] = useState({ names: [] });
const update = (categoryName, element) =>
setItems((oldItems) => ({
...oldItems,
[categoryName]: [...(oldItems[categoryName] || []), element]
}));
// example to call `update`
useEffect(() => {
update("test", "blub");
}, []);
return (
<div className="App">
{items.test?.map((item) => (
<p>{item}</p>
))}
</div>
);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…