search

Home  >  Q&A  >  body text

Insert records using 2 states

在此处查找完整的代码片段

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。 所以,在

如何修复它,以便在单击 #1 时,raw 填充 target[0] 数据?

P粉545682500P粉545682500351 days ago459

reply all(1)I'll reply

  • P粉744831602

    P粉7448316022024-02-27 14:08:07

    Follow complete code snippet

    The first useEffect was not closed, so I commented it and it worked.

    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}

    ); }

    reply
    0
  • Cancelreply