【问题标题】:React - How to get an id and use it to deleteReact - 如何获取 id 并使用它来删除
【发布时间】:2021-10-26 00:40:00
【问题描述】:

所以在反应中我做了一个按钮来删除一些数据,所以我需要通过 id 获取汽车并使用 react js axios 将其删除,所以我得到的响应是一个空数组,所以请有人帮助我。

代码如下:

在服务数据文件中:

get(id) {

  return http.get(`/get/${id}`);
}
delete(id) {

  return http.delete(`/delete/${id}`);
}

Component.jsx

 this.state = {
        idCars: null,
        carName: "",
        carModel: "", 
        cars: [],
        submitted: false
      };

     
    }
    getCar(idCars) {
      DataService.get(idCars)
        .then(response => {
          this.setState({
            cars: response.data
            
          });
          console.log(response.data);
          
        })
        .catch(e => {
          console.log(e);
        });
    }
   

    componentDidMount() {
      
      this.getCar(this.props.match.params.idCars);
      this.retrieveCars()
    }
 deleteC() {    
     

      DataService.delete(this.state.cars.idCars)
        .then(response => {
          
          this.props.history.push('/Classement');
          this.refreshList()
        })
        .catch(e => {
          console.log(e);
        });
    }
 render() {
      const { cars } = this.state;
           return (      
            <div ><tbody>
                    {
                      cars.map(data => (
                        <tr >
                        
                        <th scope="row">{data.idCars}</th>  
                      
                      <td>{data.carName}</td>
                      <td>{data.carModel}</td>
                      <td>
                 
                      <button  className="btn btn-danger"  onClick={this.deleteC}>
                        Remove
                      </button>
                        </td> 
            
                      </tr>
                      ))
                    }

并且什么都没有删除,我该如何解决这个问题

【问题讨论】:

    标签: reactjs axios crud http-delete


    【解决方案1】:

    此时您的 DeleteC 函数尝试读取:

    this.state.cars.idCars
    

    但是 this.state.cars 是一个数组,所以 idCars 只为给定的索引定义,例如:

    this.state.cars[0].idCars
    

    您可以做的是为此修改您的 onClick 行为:

    onClick={() => deleteC(data.idCars)}
    

    这样,deleteC 函数将使用所选行的 idCars 调用。

    【讨论】:

    • 我试图在点击时传递 id,但它返回未定义的 id 这是我在控制台中得到的错误:vendors~main.chunk.js:91980 DELETE localhost:3000/api/delete/undefined net::ERR_INSUFFICIENT_RESOURCES 并且错误循环
    • 现在可以了...非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    相关资源
    最近更新 更多