【发布时间】:2021-10-22 16:03:10
【问题描述】:
查看其他帖子后,我没有找到我问题的确切答案,但显然这个问题发生在其他人身上,而不是我的问题。 从下面的函数发送的每个 PUT、POST、DELETE 请求都会被调用两次。 这是我处理用户对 UI 的更改(添加、更新、删除)的功能代码。 它是 ReactJS 类组件的一部分
commitChanges({ added, changed, deleted }) {
this.setState((state) => {
let { data } = state;
if (added) {
const startingAddedId = data!=undefined && data.length > 0 ? data[data.length - 1].id + 1 : 0;
var TBname= decodeURIComponent(window.location.pathname.slice(window.location.pathname.lastIndexOf(':')+1 ));
if ( data == undefined) data = [{ id: startingAddedId, ...added} ];
data = [...data, { id: startingAddedId, ...added }];
fetch('http://localhost:3001/api/appo',
{
method: 'POST',
headers: { 'Accept': 'application/json, text/plain, */*' ,'Content-Type': 'application/json' },
body: JSON.stringify({ id: startingAddedId,"TBname": TBname, ...added } )
})
.then( (response) => this.setState({ data: data }) ) .catch(() => console.log('POST failed'));
this.setState({ data: data })
console.log(this.state.data);
}
if (changed) {
data.map((appointment) => {
console.log(changed[appointment._id]);
if (changed[appointment.id] != undefined) {
//console.log("JSON",JSON.stringify({...appointment,...changed[appointment.id],} ) );
fetch('http://localhost:3001/api/appo/'+appointment.id,
{
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({...appointment,...changed[appointment.id],} )
}).catch(() => console.log('PUT failed'));
}
});
data = data.map((appointment) =>
changed[appointment.id] ? { ...appointment, ...changed[appointment.id] } : appointment)
this.setState({ data: data });
}
if (deleted !== undefined) {
console.log(deleted);
fetch('http://localhost:3001/api/appo/'+deleted,
{
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
}).catch(() => console.log('DELETE failed'));
data = data.filter(appointment => appointment.id !== deleted);
this.setState({ data: data })
}
return { data };
});
}
例如,如果我想发送 POST 请求来创建一个项目,这个项目将被创建两次,具有相同的 id。
【问题讨论】: