Click button s"> Fill an array with key-value pairs-PHP Chinese Network Q&A
Fill an array with key-value pairs
P粉865900994
P粉865900994 2023-09-02 16:55:11
0
1
430

I'm trying to fill an array with objects. If I execute setState, new entries are not added, but the structure of the array is expanded. For example: initial entry (0), new entry (0->0), another entry (0->0->0). However, I would like each entry to have a consecutive number.

const [entrys, setEntrys] = useState([{ date: "", entry: "" }]); ->Click button setEntrys((prev) => [{ ...prev, date: clickedDay, entry: hinweis }]);
P粉865900994
P粉865900994

reply all (1)
P粉475315142

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 codesandboxhttps://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 ( 
); }; export default App;
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!