【发布时间】:2021-06-23 23:30:28
【问题描述】:
我正在尝试使用 reactjs 和 node js 以及 mysql 数据库添加和更新数据。这是我的代码。
为了连接,我在节点 js 中创建了 REST API。
连接成功实现。
这是我的前端代码
用于向数据库添加数据
const App1 = () =>{
const [data,setData] = useState({
name: '',
location: '',
record: [],
showAlert: false,
alertMsg: "",
alertType: "success",
id:"",
update: false,
});
useEffect(()=>{
fetchData();
},[]);
// const [location,setLocation] = useState({location: ''});
const InputEvent = (event) =>{
const {name, value} = event.target;
setData((preValue)=>{
return{
...preValue,
[name]: value,
};
});
};
const addData = () =>{
var myHeaders = new Headers();
myHeaders.append("Content-Type","application/json")
var body = JSON.stringify({name: data.name, location: data.location});
fetch("http://localhost:8000/api/create",{
method: "POST",
headers: myHeaders,
body: body
}).then((res)=>res.json())
.then((result)=>{
console.log(result);
setData({
name:"",
location: "",
showAlert: true,
alertMsg: result.res,
alertType: "success",
record: result.res,
});
});
};
用于从数据库中获取所有记录
const fetchData = () =>{
var headers = new Headers();
headers.append("Content-Type","application/json");
fetch("http://localhost:8000/api/view",{
method: "GET",
headers: headers,
}).then((res)=>res.json())
.then((result)=>{
console.log("result",result);
setData({
record: result.res,
})
}).catch((err)=> console.log("Error",err))};
对于在此编辑数据库中的数据,我面临编辑数据的问题,因为当单击编辑按钮时,数据库中的数据已更新但前端发生错误 =“无法访问属性” map", data.record 未定义"
编辑功能代码
const editTask = (id) =>{
fetch("http://localhost:8000/api/view/"+id,{
method: "GET",
}).then((res)=>res.json())
.then((result)=>{
console.log(result);
setData({
id: id,
update: true,
record: result.res,
name: result.res[0].name,
location: result.res[0].location,
});
}).catch((err)=>console.log("Error",err));};
现在来更新部分
这里是更新函数发生同样的错误="TypeError: can't access property "map", data.record is undefined
更新函数如下
const updateTask = () =>{
var myHeaders = new Headers();
myHeaders.append("Content-Type","application/json");
var body = JSON.stringify({id: data.id, name: data.name, location: data.location});
fetch("http://localhost:8000/api/update",{
method: "PUT",
headers: myHeaders,
body: body
}).then((res)=>res.json())
.then((result)=>{
console.log(result);
setData({
showAlert: true,
alertMsg: result.res,
alertType: "success",
update: false,
id: "",
name: "",
location: "",
});
fetchData();
}).catch((err)=>console.log("Error",err));};
现在来返回我写map方法代码的部分
data.record.map((record)=>{
return(
<tr>
<td>{record.id}</td>
<td>{record.name}</td>
<td>{record.location}</td>
<td>
<Button variant="info"onClick{()=>editTask(record.id)}>Edit</Button>
</td>
<td>
<Button variant="danger">Delete</Button>
</td>
</tr>
);
请帮帮我,谢谢
【问题讨论】:
-
你在哪里使用
data.record.map?请分享整个文件,而不是其中的一部分,因为最重要的部分是单独的...... -
你正在改变你的状态结构。首先它是一个包含所有数据的状态,但是您的编辑和更新操作会将您的状态集合更改为来自 api 的单个记录。
标签: javascript html node.js reactjs rest