【问题标题】:fetch request is called twice?fetch 请求被调用两次?
【发布时间】: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。

Double POST REQUEST

【问题讨论】:

    标签: node.js reactjs api fetch


    【解决方案1】:

    不要在 setState 回调函数中发出任何 http 请求,这不是一个好习惯,并且在状态回调中设置状态会导致此问题。

    删除 setState 回调并执行以下操作将解决您的问题。

     commitChanges({ added, changed, deleted }) {
      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 })
          }
     }
    

    【讨论】:

    • 谢谢老哥解决了我的问题。但是可以向我解释为什么在我的初始代码中发送了两次获取请求。
    猜你喜欢
    • 2012-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    • 2016-10-20
    • 1970-01-01
    相关资源
    最近更新 更多