在此处查找完整的代码片段
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>
);
}
我从数据库获取一个数组(在上面的代码中声明了示例 target 数组)。基本上,我想读取记录并将其写入不同的表。
我使用 raw 状态来存储它们。如果您看到上面的内容,它落后于 1。
所以,在
initialStatetarget[0]。如何修复它,以便在单击 #1 时,raw 填充 target[0] 数据?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
遵循完整的代码片段
第一个 useEffect 没有关闭,所以我对它发表了评论,它起作用了。
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}