i want to add user data in table by unique id and console giving me warning " Warning: Each child in a list should have a unique "key" prop."

huangapple go评论93阅读模式
英文:

i want to add user data in table by unique id and console giving me warning " Warning: Each child in a list should have a unique "key" prop."

问题

以下是您的React组件的中文翻译部分:

import axios from "axios";
import { useState } from "react";

const AddUserData: React.FC<{ getUserAxios: () => void }> = ({
  getUserAxios,
}) => {
  const [Name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassWord] = useState("");
  const [userId, setUserId] = useState(1);

  const getUserData = () => {
    const newUserData = {
      id: userId,
      Name,
      email,
      password,
    };
    axios({
      method: "post",
      url: "http://localhost:3001/addNewUser",
      data: newUserData,
    })
      .then(function (response) {
        console.log(response);
        setTimeout(() => {
          getUserAxios();
        }, 1000);
      })
      .catch(function (error) {
        console.log(error);
      });
    setName("");
    setEmail("");
    setPassWord("");
    setUserId((prevUserId) => prevUserId + 1);
  };
  return (
    <>
      <form>
        <div className="input-group mb-3">
          <span className="input-group-text" id="basic-addon1">
            &#128578;
          </span>
          <input
            type="text"
            className="form-control"
            placeholder="用户名"
            aria-label="用户名"
            aria-describedby="basic-addon1"
            value={Name}
            onChange={(e) => setName(e.target.value)}
          />
        </div>
        <div className="input-group mb-3">
          <span className="input-group-text" id="basic-addon1">
            &#128273;
          </span>
          <input
            type="text"
            className="form-control"
            placeholder="用户姓"
            aria-label="用户姓"
            aria-describedby="basic-addon1"
            value={password}
            onChange={(e) => setPassWord(e.target.value)}
          />
        </div>
        <div className="input-group mb-3">
          <span className="input-group-text" id="basic-addon2">
            &#128140;
          </span>
          <input
            type="text"
            className="form-control"
            placeholder="用户邮箱"
            aria-label="用户邮箱"
            aria-describedby="basic-addon2"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />
        </div>
        <button
          type="button"
          className="btn btn-primary mx-2"
          onClick={getUserData}
        >
          添加
        </button>
        <button type="button" className="btn btn-secondary">
          取消
        </button>
      </form>
    </>
  );
};

export default AddUserData;
import axios from "axios";
import { useEffect, useState } from "react";
import AddUserData from "../AddUserData/AddUserData";
import { UserType } from "../store/stype-store";

const UserDataTable = () => {
  const [users, setUsers] = useState<UserType[]>([]);

  const getUserAxios = () => {
    axios
      .get("http://localhost:3001/usersData")
      .then((res) => {
        console.log("来自axios的响应", res.data);
        const { allUsers } = res.data;
        console.log("来自axios的allUsers", allUsers);
        setUsers(allUsers);
      })
      .catch((err) => {
        console.log("来自axios的错误", err.message);
      });
  };
  useEffect(() => {
    getUserAxios();
  }, []);

  const userMap = users.map((user: UserType, index) => {
    return (
      <tr key={user.id}>
        <th scope="row">{index}</th>
        <td>{user.Name}</td>
        <td>{user.password}</td>
        <td>{user.email}</td>
      </tr>
    );
  });

  return (
    <>
      <div className="col-lg-7 p-3 p-lg-5 pt-lg-3 ">
        <table className="table table-striped">
          <thead>
            <tr>
              <th scope="col">ID</th>
              <th scope="col">名称</th>
              <th scope="col">密码</th>
              <th scope="col">邮箱</th>
            </tr>
          </thead>
          <tbody>{userMap}</tbody>
        </table>
      </div>
      <div className="col-lg-4 p-3 p-lg-5 pt-lg-3">
        <AddUserData getUserAxios={getUserAxios} />
      </div>
    </>
  );
};

export default UserDataTable;
const express = require("express");
const cors = require("cors");
const app = express();

const port = 3001;

app.use(express.json());
app.use(
  cors({
    origin: "*",
  })
);

let previousUserData = [
  {
    id: 1,
    Name: "RAHUL",
    password: "1w2e2w",
    email: "affj@gmail.com",
  },
  {
    id: 2,
    Name: "CHAHUL",
    password: "1w2e2w",
    email: "affj@gmail.com",
  },
];

app.get("/usersData", (req, res) => {
  res.send({ status: 200, allUsers: previousUserData });
});

let nextUserId = 3; // 记录下一个用户的ID

app.post("/addNewUser", (req, res) => {
  const { Name, password, email } = req.body;
  if (Name && password && email) {
    const id = nextUserId++; // 分配新的用户ID
    previousUserData = [...previousUserData, { id, Name, password, email }];
    res.send({ status: 200, msg: "用户已添加", allUsers: previousUserData });
  } else {
    res.send({ status: 500, msg: "出现错误" });
  }
});

app.listen(port, () => {
  console.log("服务器已启动,端口:" + port);
});

我已经为每个用户添加了唯一的ID,并删除了键(prop)的值。如果您有其他问题或需要进一步的帮助,请告诉我。

英文:

here is my adduser react component

import axios from &quot;axios&quot;;
import { useState } from &quot;react&quot;;

const AddUserData: React.FC&lt;{ getUserAxios: () =&gt; void }&gt; = ({
  getUserAxios,
}) =&gt; {
  const [Name, setName] = useState(&quot;&quot;);
  const [email, setEmail] = useState(&quot;&quot;);
  const [password, setPassWord] = useState(&quot;&quot;);
  const [userId, setUserId] = useState(1);

  const getUserData = () =&gt; {
    const newUserData = {
      id:userId,
      Name,
      email,
      password,
    };
    axios({
      method: &quot;post&quot;,
      url: &quot;http://localhost:3001/addNewUser&quot;,
      data: newUserData,
    })
      .then(function (response) {
        console.log(response);
        setTimeout(() =&gt; {
          getUserAxios();
        }, 1000);
      })
      .catch(function (error) {
        console.log(error);
      });
    setName(&quot;&quot;);
    setEmail(&quot;&quot;);
    setPassWord(&quot;&quot;);
     setUserId((prevUserId) =&gt; prevUserId + 1);
  };
  return (
    &lt;&gt;
      &lt;form&gt;
        &lt;div className=&quot;input-group mb-3&quot;&gt;
          &lt;span className=&quot;input-group-text&quot; id=&quot;basic-addon1&quot;&gt;
            &#128578;
          &lt;/span&gt;
          &lt;input
            type=&quot;text&quot;
            className=&quot;form-control&quot;
            placeholder=&quot;User Firstname&quot;
            aria-label=&quot;User Firstname&quot;
            aria-describedby=&quot;basic-addon1&quot;
            value={Name}
            onChange={(e) =&gt; setName(e.target.value)}
          /&gt;
        &lt;/div&gt;
        &lt;div className=&quot;input-group mb-3&quot;&gt;
          &lt;span className=&quot;input-group-text&quot; id=&quot;basic-addon1&quot;&gt;
            &#128273;
          &lt;/span&gt;
          &lt;input
            type=&quot;text&quot;
            className=&quot;form-control&quot;
            placeholder=&quot;User Lastname&quot;
            aria-label=&quot;User Lastname&quot;
            aria-describedby=&quot;basic-addon1&quot;
            value={password}
            onChange={(e) =&gt; setPassWord(e.target.value)}
          /&gt;
        &lt;/div&gt;
        &lt;div className=&quot;input-group mb-3&quot;&gt;
          &lt;span className=&quot;input-group-text&quot; id=&quot;basic-addon2&quot;&gt;
            &#128140;
          &lt;/span&gt;
          &lt;input
            type=&quot;text&quot;
            className=&quot;form-control&quot;
            placeholder=&quot;Users Email&quot;
            aria-label=&quot;Users Email&quot;
            aria-describedby=&quot;basic-addon2&quot;
            value={email}
            onChange={(e) =&gt; setEmail(e.target.value)}
          /&gt;
        &lt;/div&gt;
        &lt;button
          type=&quot;button&quot;
          className=&quot;btn btn-primary mx-2&quot;
          onClick={getUserData}
        &gt;
          Add
        &lt;/button&gt;
        &lt;button type=&quot;button&quot; className=&quot;btn btn-secondary&quot;&gt;
          Cancel
        &lt;/button&gt;
      &lt;/form&gt;
    &lt;/&gt;
  );
};

export default AddUserData;

and here is my another compo

import axios from &quot;axios&quot;;
import { useEffect, useState } from &quot;react&quot;;
import AddUserData from &quot;../AddUserData/AddUserData&quot;;
import { UserType } from &quot;../store/stype-store&quot;;

const UserDataTable = () =&gt; {
  const [users, setUsers] = useState &lt;UserType[]&gt;([]);

  const getUserAxios = () =&gt; {
    axios
      .get(&quot;http://localhost:3001/usersData&quot;)
      .then((res) =&gt; {
        console.log(&quot;Response from axios&quot;, res.data);
        const { allUsers } = res.data;
        console.log(&quot;allUsers from axios&quot;, allUsers);
        setUsers(allUsers);
      })
      .catch((err) =&gt; {
        console.log(&quot;err from axios&quot;, err.message);
      });
  };
  useEffect(() =&gt; {
    getUserAxios();
  }, []);

  const userMap = users.map((user: UserType, index) =&gt; {
    return (
      &lt;tr key={user.id}&gt;
        &lt;th scope=&quot;row&quot;&gt;{index}&lt;/th&gt;
        &lt;td&gt;{user.Name}&lt;/td&gt;
        &lt;td&gt;{user.password}&lt;/td&gt;
        &lt;td&gt;{user.email}&lt;/td&gt;
      &lt;/tr&gt;
    );
  });

  return (
    &lt;&gt;
      &lt;div className=&quot;col-lg-7 p-3 p-lg-5 pt-lg-3 &quot;&gt;
        &lt;table className=&quot;table table-striped&quot;&gt;
          &lt;thead&gt;
            &lt;tr&gt;
              &lt;th scope=&quot;col&quot;&gt;ID&lt;/th&gt;
              &lt;th scope=&quot;col&quot;&gt;Name&lt;/th&gt;
              &lt;th scope=&quot;col&quot;&gt;Password&lt;/th&gt;
              &lt;th scope=&quot;col&quot;&gt;E-Mail&lt;/th&gt;
            &lt;/tr&gt;
          &lt;/thead&gt;
          &lt;tbody&gt;{userMap}&lt;/tbody&gt;
        &lt;/table&gt;
      &lt;/div&gt;
      &lt;div className=&quot;col-lg-4 p-3 p-lg-5 pt-lg-3&quot;&gt;
        &lt;AddUserData getUserAxios={getUserAxios} /&gt;
      &lt;/div&gt;
    &lt;/&gt;
  );
};

export default UserDataTable;

and here is my node server

const express = require(&quot;express&quot;);
const cors = require(&quot;cors&quot;);
const app = express();

const port = 3001;

app.use(express.json());
app.use(
  cors({
    origin: &quot;*&quot;,
  })
);

let previousUserData = [
  {
    id: 1,
    Name: &quot;RAHUL&quot;,
    password: &quot;1w2e2w&quot;,
    email: &quot;affj@gmail.com&quot;,
  },
  {
    id:2,
    Name: &quot;CHAHUL&quot;,
    password: &quot;1w2e2w&quot;,
    email: &quot;affj@gmail.com&quot;,
  },
];

app.get(&quot;/usersData&quot;, (req, res) =&gt; {
  res.send({ status: 200, allUsers: previousUserData });
});


app.post(&quot;/addNewUser&quot;, (req, res) =&gt; {
  const { id, Name, password, email } = req.body;
  if (Name &amp;&amp; password &amp;&amp; email) {
    previousUserData = [...previousUserData, { id, Name, password, email }];
    res.send({ status: 200, msg: &quot;user added&quot;, allUsers: previousUserData });
  } else {
    res.send({ status: 500, msg: &quot;something went wrong&quot; });
  }
});

app.listen(port, () =&gt; {
  console.log(&quot;Server started on port &quot; + port);
});

I want give an unique id to each user if we add another one and also want remove the key prop value

答案1

得分: 1

这段代码将与您的 previousUserData 冲突,因为它已经有一个 id: 1 的记录。

我建议 不要 在客户端分配记录的ID。相反,开发一个服务器端的策略来生成ID。

在您的情况下,可以简单地使用以下方法:

const getNextId = () => previousUserData.length;

// 或者如果您想要更好的保证
// const getNextId = () => Math.max(...previousUserData.map(({ id }) => id)) + 1;

app.post("/addNewUser", (req, res) => {
  const { Name, password, email } = req.body;
  if (Name && password && email) {
    previousUserData.push({
      id: getNextId(),
      Name,
      password,
      email,
    });
    res.json({ msg: "user added", allUsers: previousUserData });
  } else {
    res.status(500).send({ msg: "something went wrong" });
  }
});
英文:

> lang-js
&gt; const [userId, setUserId] = useState(1);
&gt;

This code is going to conflict with your previousUserData which already has an id: 1 record.

I would recommend not assigning the record ID from the client-side. Instead, develop a server-side strategy for generating IDs.

In your case it could be as simple as the following

const getNextId = () =&gt; previousUserData.length;

// or if you want a better guarantee
// const getNextId = () =&gt; Math.max(...previousUserData.map(({ id }) =&gt; id)) + 1;

app.post(&quot;/addNewUser&quot;, (req, res) =&gt; {
  const { Name, password, email } = req.body;
  if (Name &amp;&amp; password &amp;&amp; email) {
    previousUserData.push({
      id: getNextId(),
      Name,
      password,
      email,
    });
    res.json({ msg: &quot;user added&quot;, allUsers: previousUserData });
  } else {
    res.status(500).send({ msg: &quot;something went wrong&quot; });
  }
});

huangapple
  • 本文由 发表于 2023年5月25日 14:03:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76329336.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定