P粉4753151422023-09-03 10:59:11
The problem you encounter is that you are using a previous state in the object you pass, for example using the spread operator "prev".
What you want to do is include the previous state in the new object saved to state, e.g. "prev" as a separate element in the array - like below.
I also provide you with a codesandbox https://codesandbox.io/s/romantic-solomon-l566yy?file=/src/App.js.
import "./styles.css"; import React, { useState } from "react"; const App = () => { const [entries, setEntries] = useState([ { date: "", text: "" } ]); const handleClick = () => { setEntries((prevEntry) => { return [...prevEntry, { date: "date", text: "test" }]; }); }; return ( <div> <button onClick={handleClick}>Click me!</button> </div> ); }; export default App;