使用React+Axios提交编辑数据到后端更新MongoDB时参数未更新问题
问题原因
- 你当前使用的输入框是非受控组件,仅将接口返回的初始
location值作为占位符展示,用户输入的内容没有同步更新到组件的state中 - 点击提交编辑按钮时,传递给
editById方法的location仍然是接口返回的原始旧数据,不是用户修改后的新值,因此参数传递错误
修复方案
我们将输入框改为React受控组件,把用户输入的内容实时同步到state中,修改后的完整代码如下:
import { render } from "react-dom"; import React, { Component } from "react"; import axios from "axios"; import "../styles/TourPage.css"; class TourPage extends Component { constructor(props) { super(props); this.state = { myData: [], isLoading: true }; } componentDidMount() { axios .get("/getResults") .then((res) => { this.setState({ myData: res.data }); }) .catch((error) => { // Handle the errors here console.log(error); }) .finally(() => { this.setState({ isLoading: false }); }); } deleteById = (id) => { console.log(id) axios .post(`/deleteDoc`, {id: id} ) .then(() => { console.log(id, " worked") window.location = "/tour" }) .catch((error) => { // Handle the errors here console.log(error); }) } // 新增方法:实时更新对应条目的location值 handleLocationChange = (index, newValue) => { const updatedData = [...this.state.myData] updatedData[index].location = newValue this.setState({ myData: updatedData }) } editById = (id, location, Services, cnum) => { console.log(id, location, Services, cnum) axios .post(`/editDoc`, {id: id, location: location, Services: Services, cnum: cnum} ) .then(() => { console.log(id, " worked") window.location = "/tour" }) .catch((error) => { // Handle the errors here console.log(error); }) } render() { let { myData, isLoading } = this.state; return ( <table id="customers"> <tr> <th>siteLocation</th> <th>Services</th> <th>cnum</th> </tr> {myData.length > 0 ? myData.map(({ location, Services, cnum, _id }, index) => ( <tr key={index}> {/* 修改输入框为受控组件,绑定值和输入事件 */} <td> <input type="text" placeholder={location} value={location} onChange={(e) => this.handleLocationChange(index, e.target.value)} /> </td> <td>{Services}</td> <td>{cnum}</td> <button onClick={() => this.deleteById(_id)} disabled={isLoading} > Delete </button> <button onClick={() => this.editById(_id, location, Services, cnum)} disabled={isLoading} > Submit Edit </button> </tr> )) : "No Data Found"} </table> ); } } export default TourPage;
核心修改说明
- 新增
handleLocationChange方法,接收数组下标和用户输入的新值,更新state中对应条目的location字段 - 将原来的输入框改为受控组件,绑定
value为当前条目的location值,输入变化时触发handleLocationChange更新state - state更新后,映射渲染时拿到的
location就是用户修改后的最新值,点击提交编辑时就能把正确的参数传给后端
如果后续需要编辑Services和cnum字段,按照同样的逻辑添加对应的修改方法和输入框绑定即可。
内容的提问来源于stack exchange,提问作者developerg1000
相关产品推荐
相关产品推荐

