reactjs - React.js MERN 应用程序:Axios 删除路由未读取道具(范围问题)
问题描述
import React, { Component } from "react";
import axios from "axios";
import { Link } from "react-router-dom";
import { Button } from "react-bootstrap";
export default class DeleteTodo extends Component {
constructor(props) {
super(props);
this.state = {
todo_description: "",
todo_responsible: "",
todo_id: this.props.match.params.id,
};
console.log(this.props.match.params.id);
}
onSubmit(e) {
e.preventDefault();
axios
.post("http://localhost:4000/todos/delete/" + this.props.match.params.id)
.then((res) => console.log(res.data));
this.props.history.push("/");
}
render() {
console.log(this.props.match.params.id);
return (
<div>
<h3 align="center">Confirm Delete</h3>
<form onSubmit={this.onSubmit}>
<div>
<b className="d-inline">Description: </b>
<p className="d-inline">{this.state.todo_description}</p>
</div>
<div>
<b className="d-inline">Responsible: </b>
<p className="d-inline">{this.state.todo_responsible}</p>
</div>
<br />
<div>
<Button size="sm" type="submit" variant="danger">
Delete
</Button>
 
<Link to={"/"}>
<Button size="sm" variant="info">
Undo
</Button>
</Link>
</div>
</form>
</div>
);
}
}
我想将对象的 ID 添加到 Axios 发布路由。
console.log(this.props.match.params.id); 将在构造函数和渲染中记录 ID,但 props 在 Axios 调用中显示为 undefined。如何在 onSubmit() 中获取要租用的 ID?
解决方案
您的问题是您的函数与本机反应函数onSubmit
没有相同的变量。this
为了解决这个问题,您需要将函数与组件对象绑定。
您可以在此处阅读有关此内容的更多信息:https ://reactjs.org/docs/handling-events.html
将您的文件替换为以下内容:
import React, { Component } from "react";
import axios from "axios";
import { Link } from "react-router-dom";
import { Button } from "react-bootstrap";
export default class DeleteTodo extends Component {
constructor(props) {
super(props);
this.state = {
todo_description: "",
todo_responsible: "",
todo_id: this.props.match.params.id,
};
this.onSubmit = this.onSubmit.bind(this) // new line added
console.log(this.props.match.params.id);
}
onSubmit(e) {
e.preventDefault();
axios
.post("http://localhost:4000/todos/delete/" + this.props.match.params.id)
.then((res) => console.log(res.data));
this.props.history.push("/");
}
render() {
console.log(this.props.match.params.id);
return (
<div>
<h3 align="center">Confirm Delete</h3>
<form onSubmit={this.onSubmit}>
<div>
<b className="d-inline">Description: </b>
<p className="d-inline">{this.state.todo_description}</p>
</div>
<div>
<b className="d-inline">Responsible: </b>
<p className="d-inline">{this.state.todo_responsible}</p>
</div>
<br />
<div>
<Button size="sm" type="submit" variant="danger">
Delete
</Button>
 
<Link to={"/"}>
<Button size="sm" variant="info">
Undo
</Button>
</Link>
</div>
</form>
</div>
);
}
}