Rumah > Soal Jawab > teks badan
Cari coretan kod lengkap di sini
import "./styles.css"; import React, { useState } from "react"; export default function App() { const target = [ { id: 16, word: "sixteen" }, { id: 17, word: "seventeen" }, { id: 18, word: "eighteen" } ]; const initialState = { tid: "", name: "" }; const [count, setCount] = useState(0); const [raw, setRaw] = useState(initialState); function change() { setRaw((raw) => ({ ...raw, tid: target[count]?.id })); setRaw((raw) => ({ ...raw, name: target[count].word })); console.log(raw); //axios function to insert record setCount((count) => count + 1); } return ( <div className="App"> <h1 onClick={change}>Click</h1> <h2>Count : {count}</h2> <h2> Array: {target[count]?.id},{target[count].word} </h2> <h2> State Object : {raw.tid},{raw.name} </h2> </div> ); }
Saya mendapat tatasusunan daripada pangkalan data (contoh target
tatasusunan diisytiharkan dalam kod di atas). Pada asasnya, saya mahu membaca rekod dan menulisnya ke jadual yang berbeza.
Saya guna raw
状态来存储它们。如果您看到上面的内容,它落后于 1
.
Jadi, dalam
initialState
target[0]
. Bagaimana untuk membetulkannya supaya apabila #1 diklik, raw
填充 target[0]
data?
P粉7448316022024-02-27 14:08:07
Ikuti coretan kod yang lengkap< /a>
Kesan penggunaan pertama tidak ditutup, jadi saya mengulasnya dan ia berkesan.
import "./styles.css"; import React, { useState,useEffect } from "react"; export default function App() { // useEffect ( () => { const target = [ { id: 16, word: "sixteen" }, { id: 17, word: "seventeen" }, { id: 18, word: "eighteen" } ]; const initialState = { tid: 0, //target[0]?.id, name: "A" //target[0]?.word }; const [count, setCount] = useState(0); const [raw, setRaw] = useState(initialState); useEffect ( () => { setRaw((raw) => ({ ...raw, tid: target[count]?.id })); setRaw((raw) => ({ ...raw, name: target[count].word })); }, [count]) function change() { console.log(raw); //axios function to insert record setCount((count) => count + 1); } return (); }Click
Count : {count}
Array: {target[count]?.id}{target[count].word}
State Object : {raw.tid},{raw.name}