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评论123阅读模式
英文:

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组件的中文翻译部分:

  1. import axios from "axios";
  2. import { useState } from "react";
  3. const AddUserData: React.FC<{ getUserAxios: () => void }> = ({
  4. getUserAxios,
  5. }) => {
  6. const [Name, setName] = useState("");
  7. const [email, setEmail] = useState("");
  8. const [password, setPassWord] = useState("");
  9. const [userId, setUserId] = useState(1);
  10. const getUserData = () => {
  11. const newUserData = {
  12. id: userId,
  13. Name,
  14. email,
  15. password,
  16. };
  17. axios({
  18. method: "post",
  19. url: "http://localhost:3001/addNewUser",
  20. data: newUserData,
  21. })
  22. .then(function (response) {
  23. console.log(response);
  24. setTimeout(() => {
  25. getUserAxios();
  26. }, 1000);
  27. })
  28. .catch(function (error) {
  29. console.log(error);
  30. });
  31. setName("");
  32. setEmail("");
  33. setPassWord("");
  34. setUserId((prevUserId) => prevUserId + 1);
  35. };
  36. return (
  37. <>
  38. <form>
  39. <div className="input-group mb-3">
  40. <span className="input-group-text" id="basic-addon1">
  41. &#128578;
  42. </span>
  43. <input
  44. type="text"
  45. className="form-control"
  46. placeholder="用户名"
  47. aria-label="用户名"
  48. aria-describedby="basic-addon1"
  49. value={Name}
  50. onChange={(e) => setName(e.target.value)}
  51. />
  52. </div>
  53. <div className="input-group mb-3">
  54. <span className="input-group-text" id="basic-addon1">
  55. &#128273;
  56. </span>
  57. <input
  58. type="text"
  59. className="form-control"
  60. placeholder="用户姓"
  61. aria-label="用户姓"
  62. aria-describedby="basic-addon1"
  63. value={password}
  64. onChange={(e) => setPassWord(e.target.value)}
  65. />
  66. </div>
  67. <div className="input-group mb-3">
  68. <span className="input-group-text" id="basic-addon2">
  69. &#128140;
  70. </span>
  71. <input
  72. type="text"
  73. className="form-control"
  74. placeholder="用户邮箱"
  75. aria-label="用户邮箱"
  76. aria-describedby="basic-addon2"
  77. value={email}
  78. onChange={(e) => setEmail(e.target.value)}
  79. />
  80. </div>
  81. <button
  82. type="button"
  83. className="btn btn-primary mx-2"
  84. onClick={getUserData}
  85. >
  86. 添加
  87. </button>
  88. <button type="button" className="btn btn-secondary">
  89. 取消
  90. </button>
  91. </form>
  92. </>
  93. );
  94. };
  95. export default AddUserData;
  1. import axios from "axios";
  2. import { useEffect, useState } from "react";
  3. import AddUserData from "../AddUserData/AddUserData";
  4. import { UserType } from "../store/stype-store";
  5. const UserDataTable = () => {
  6. const [users, setUsers] = useState<UserType[]>([]);
  7. const getUserAxios = () => {
  8. axios
  9. .get("http://localhost:3001/usersData")
  10. .then((res) => {
  11. console.log("来自axios的响应", res.data);
  12. const { allUsers } = res.data;
  13. console.log("来自axios的allUsers", allUsers);
  14. setUsers(allUsers);
  15. })
  16. .catch((err) => {
  17. console.log("来自axios的错误", err.message);
  18. });
  19. };
  20. useEffect(() => {
  21. getUserAxios();
  22. }, []);
  23. const userMap = users.map((user: UserType, index) => {
  24. return (
  25. <tr key={user.id}>
  26. <th scope="row">{index}</th>
  27. <td>{user.Name}</td>
  28. <td>{user.password}</td>
  29. <td>{user.email}</td>
  30. </tr>
  31. );
  32. });
  33. return (
  34. <>
  35. <div className="col-lg-7 p-3 p-lg-5 pt-lg-3 ">
  36. <table className="table table-striped">
  37. <thead>
  38. <tr>
  39. <th scope="col">ID</th>
  40. <th scope="col">名称</th>
  41. <th scope="col">密码</th>
  42. <th scope="col">邮箱</th>
  43. </tr>
  44. </thead>
  45. <tbody>{userMap}</tbody>
  46. </table>
  47. </div>
  48. <div className="col-lg-4 p-3 p-lg-5 pt-lg-3">
  49. <AddUserData getUserAxios={getUserAxios} />
  50. </div>
  51. </>
  52. );
  53. };
  54. export default UserDataTable;
  1. const express = require("express");
  2. const cors = require("cors");
  3. const app = express();
  4. const port = 3001;
  5. app.use(express.json());
  6. app.use(
  7. cors({
  8. origin: "*",
  9. })
  10. );
  11. let previousUserData = [
  12. {
  13. id: 1,
  14. Name: "RAHUL",
  15. password: "1w2e2w",
  16. email: "affj@gmail.com",
  17. },
  18. {
  19. id: 2,
  20. Name: "CHAHUL",
  21. password: "1w2e2w",
  22. email: "affj@gmail.com",
  23. },
  24. ];
  25. app.get("/usersData", (req, res) => {
  26. res.send({ status: 200, allUsers: previousUserData });
  27. });
  28. let nextUserId = 3; // 记录下一个用户的ID
  29. app.post("/addNewUser", (req, res) => {
  30. const { Name, password, email } = req.body;
  31. if (Name && password && email) {
  32. const id = nextUserId++; // 分配新的用户ID
  33. previousUserData = [...previousUserData, { id, Name, password, email }];
  34. res.send({ status: 200, msg: "用户已添加", allUsers: previousUserData });
  35. } else {
  36. res.send({ status: 500, msg: "出现错误" });
  37. }
  38. });
  39. app.listen(port, () => {
  40. console.log("服务器已启动,端口:" + port);
  41. });

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

英文:

here is my adduser react component

  1. import axios from &quot;axios&quot;;
  2. import { useState } from &quot;react&quot;;
  3. const AddUserData: React.FC&lt;{ getUserAxios: () =&gt; void }&gt; = ({
  4. getUserAxios,
  5. }) =&gt; {
  6. const [Name, setName] = useState(&quot;&quot;);
  7. const [email, setEmail] = useState(&quot;&quot;);
  8. const [password, setPassWord] = useState(&quot;&quot;);
  9. const [userId, setUserId] = useState(1);
  10. const getUserData = () =&gt; {
  11. const newUserData = {
  12. id:userId,
  13. Name,
  14. email,
  15. password,
  16. };
  17. axios({
  18. method: &quot;post&quot;,
  19. url: &quot;http://localhost:3001/addNewUser&quot;,
  20. data: newUserData,
  21. })
  22. .then(function (response) {
  23. console.log(response);
  24. setTimeout(() =&gt; {
  25. getUserAxios();
  26. }, 1000);
  27. })
  28. .catch(function (error) {
  29. console.log(error);
  30. });
  31. setName(&quot;&quot;);
  32. setEmail(&quot;&quot;);
  33. setPassWord(&quot;&quot;);
  34. setUserId((prevUserId) =&gt; prevUserId + 1);
  35. };
  36. return (
  37. &lt;&gt;
  38. &lt;form&gt;
  39. &lt;div className=&quot;input-group mb-3&quot;&gt;
  40. &lt;span className=&quot;input-group-text&quot; id=&quot;basic-addon1&quot;&gt;
  41. &#128578;
  42. &lt;/span&gt;
  43. &lt;input
  44. type=&quot;text&quot;
  45. className=&quot;form-control&quot;
  46. placeholder=&quot;User Firstname&quot;
  47. aria-label=&quot;User Firstname&quot;
  48. aria-describedby=&quot;basic-addon1&quot;
  49. value={Name}
  50. onChange={(e) =&gt; setName(e.target.value)}
  51. /&gt;
  52. &lt;/div&gt;
  53. &lt;div className=&quot;input-group mb-3&quot;&gt;
  54. &lt;span className=&quot;input-group-text&quot; id=&quot;basic-addon1&quot;&gt;
  55. &#128273;
  56. &lt;/span&gt;
  57. &lt;input
  58. type=&quot;text&quot;
  59. className=&quot;form-control&quot;
  60. placeholder=&quot;User Lastname&quot;
  61. aria-label=&quot;User Lastname&quot;
  62. aria-describedby=&quot;basic-addon1&quot;
  63. value={password}
  64. onChange={(e) =&gt; setPassWord(e.target.value)}
  65. /&gt;
  66. &lt;/div&gt;
  67. &lt;div className=&quot;input-group mb-3&quot;&gt;
  68. &lt;span className=&quot;input-group-text&quot; id=&quot;basic-addon2&quot;&gt;
  69. &#128140;
  70. &lt;/span&gt;
  71. &lt;input
  72. type=&quot;text&quot;
  73. className=&quot;form-control&quot;
  74. placeholder=&quot;Users Email&quot;
  75. aria-label=&quot;Users Email&quot;
  76. aria-describedby=&quot;basic-addon2&quot;
  77. value={email}
  78. onChange={(e) =&gt; setEmail(e.target.value)}
  79. /&gt;
  80. &lt;/div&gt;
  81. &lt;button
  82. type=&quot;button&quot;
  83. className=&quot;btn btn-primary mx-2&quot;
  84. onClick={getUserData}
  85. &gt;
  86. Add
  87. &lt;/button&gt;
  88. &lt;button type=&quot;button&quot; className=&quot;btn btn-secondary&quot;&gt;
  89. Cancel
  90. &lt;/button&gt;
  91. &lt;/form&gt;
  92. &lt;/&gt;
  93. );
  94. };
  95. export default AddUserData;

and here is my another compo

  1. import axios from &quot;axios&quot;;
  2. import { useEffect, useState } from &quot;react&quot;;
  3. import AddUserData from &quot;../AddUserData/AddUserData&quot;;
  4. import { UserType } from &quot;../store/stype-store&quot;;
  5. const UserDataTable = () =&gt; {
  6. const [users, setUsers] = useState &lt;UserType[]&gt;([]);
  7. const getUserAxios = () =&gt; {
  8. axios
  9. .get(&quot;http://localhost:3001/usersData&quot;)
  10. .then((res) =&gt; {
  11. console.log(&quot;Response from axios&quot;, res.data);
  12. const { allUsers } = res.data;
  13. console.log(&quot;allUsers from axios&quot;, allUsers);
  14. setUsers(allUsers);
  15. })
  16. .catch((err) =&gt; {
  17. console.log(&quot;err from axios&quot;, err.message);
  18. });
  19. };
  20. useEffect(() =&gt; {
  21. getUserAxios();
  22. }, []);
  23. const userMap = users.map((user: UserType, index) =&gt; {
  24. return (
  25. &lt;tr key={user.id}&gt;
  26. &lt;th scope=&quot;row&quot;&gt;{index}&lt;/th&gt;
  27. &lt;td&gt;{user.Name}&lt;/td&gt;
  28. &lt;td&gt;{user.password}&lt;/td&gt;
  29. &lt;td&gt;{user.email}&lt;/td&gt;
  30. &lt;/tr&gt;
  31. );
  32. });
  33. return (
  34. &lt;&gt;
  35. &lt;div className=&quot;col-lg-7 p-3 p-lg-5 pt-lg-3 &quot;&gt;
  36. &lt;table className=&quot;table table-striped&quot;&gt;
  37. &lt;thead&gt;
  38. &lt;tr&gt;
  39. &lt;th scope=&quot;col&quot;&gt;ID&lt;/th&gt;
  40. &lt;th scope=&quot;col&quot;&gt;Name&lt;/th&gt;
  41. &lt;th scope=&quot;col&quot;&gt;Password&lt;/th&gt;
  42. &lt;th scope=&quot;col&quot;&gt;E-Mail&lt;/th&gt;
  43. &lt;/tr&gt;
  44. &lt;/thead&gt;
  45. &lt;tbody&gt;{userMap}&lt;/tbody&gt;
  46. &lt;/table&gt;
  47. &lt;/div&gt;
  48. &lt;div className=&quot;col-lg-4 p-3 p-lg-5 pt-lg-3&quot;&gt;
  49. &lt;AddUserData getUserAxios={getUserAxios} /&gt;
  50. &lt;/div&gt;
  51. &lt;/&gt;
  52. );
  53. };
  54. export default UserDataTable;

and here is my node server

  1. const express = require(&quot;express&quot;);
  2. const cors = require(&quot;cors&quot;);
  3. const app = express();
  4. const port = 3001;
  5. app.use(express.json());
  6. app.use(
  7. cors({
  8. origin: &quot;*&quot;,
  9. })
  10. );
  11. let previousUserData = [
  12. {
  13. id: 1,
  14. Name: &quot;RAHUL&quot;,
  15. password: &quot;1w2e2w&quot;,
  16. email: &quot;affj@gmail.com&quot;,
  17. },
  18. {
  19. id:2,
  20. Name: &quot;CHAHUL&quot;,
  21. password: &quot;1w2e2w&quot;,
  22. email: &quot;affj@gmail.com&quot;,
  23. },
  24. ];
  25. app.get(&quot;/usersData&quot;, (req, res) =&gt; {
  26. res.send({ status: 200, allUsers: previousUserData });
  27. });
  28. app.post(&quot;/addNewUser&quot;, (req, res) =&gt; {
  29. const { id, Name, password, email } = req.body;
  30. if (Name &amp;&amp; password &amp;&amp; email) {
  31. previousUserData = [...previousUserData, { id, Name, password, email }];
  32. res.send({ status: 200, msg: &quot;user added&quot;, allUsers: previousUserData });
  33. } else {
  34. res.send({ status: 500, msg: &quot;something went wrong&quot; });
  35. }
  36. });
  37. app.listen(port, () =&gt; {
  38. console.log(&quot;Server started on port &quot; + port);
  39. });

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。

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

  1. const getNextId = () => previousUserData.length;
  2. // 或者如果您想要更好的保证
  3. // const getNextId = () => Math.max(...previousUserData.map(({ id }) => id)) + 1;
  4. app.post("/addNewUser", (req, res) => {
  5. const { Name, password, email } = req.body;
  6. if (Name && password && email) {
  7. previousUserData.push({
  8. id: getNextId(),
  9. Name,
  10. password,
  11. email,
  12. });
  13. res.json({ msg: "user added", allUsers: previousUserData });
  14. } else {
  15. res.status(500).send({ msg: "something went wrong" });
  16. }
  17. });
英文:

> 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

  1. const getNextId = () =&gt; previousUserData.length;
  2. // or if you want a better guarantee
  3. // const getNextId = () =&gt; Math.max(...previousUserData.map(({ id }) =&gt; id)) + 1;
  4. app.post(&quot;/addNewUser&quot;, (req, res) =&gt; {
  5. const { Name, password, email } = req.body;
  6. if (Name &amp;&amp; password &amp;&amp; email) {
  7. previousUserData.push({
  8. id: getNextId(),
  9. Name,
  10. password,
  11. email,
  12. });
  13. res.json({ msg: &quot;user added&quot;, allUsers: previousUserData });
  14. } else {
  15. res.status(500).send({ msg: &quot;something went wrong&quot; });
  16. }
  17. });

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:

确定