英文:
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">
🙂
</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">
🔑
</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">
💌
</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 "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">
🙂
</span>
<input
type="text"
className="form-control"
placeholder="User Firstname"
aria-label="User Firstname"
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">
🔑
</span>
<input
type="text"
className="form-control"
placeholder="User Lastname"
aria-label="User Lastname"
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">
💌
</span>
<input
type="text"
className="form-control"
placeholder="Users Email"
aria-label="Users Email"
aria-describedby="basic-addon2"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<button
type="button"
className="btn btn-primary mx-2"
onClick={getUserData}
>
Add
</button>
<button type="button" className="btn btn-secondary">
Cancel
</button>
</form>
</>
);
};
export default AddUserData;
and here is my another compo
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("Response from axios", res.data);
const { allUsers } = res.data;
console.log("allUsers from axios", allUsers);
setUsers(allUsers);
})
.catch((err) => {
console.log("err from 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">Name</th>
<th scope="col">Password</th>
<th scope="col">E-Mail</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;
and here is my node server
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 });
});
app.post("/addNewUser", (req, res) => {
const { id, Name, password, email } = req.body;
if (Name && password && email) {
previousUserData = [...previousUserData, { id, Name, password, email }];
res.send({ status: 200, msg: "user added", allUsers: previousUserData });
} else {
res.send({ status: 500, msg: "something went wrong" });
}
});
app.listen(port, () => {
console.log("Server started on port " + 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
> const [userId, setUserId] = useState(1);
>
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 = () => previousUserData.length;
// or if you want a better guarantee
// 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" });
}
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论