如果在React组件内使用axios进行post请求时出现问题,可以尝试使用箭头函数(Lambda表达式)来绑定事件处理程序和调用函数。例如:
import React, { Component } from 'react';
import axios from 'axios';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
email: ''
};
}
handleInputChange = (event) => {
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
});
}
handleSubmit = (event) => {
event.preventDefault();
const user = {
name: this.state.name,
email: this.state.email
};
axios.post('/api/users', user)
.then(res => {
console.log(res);
console.log(res.data);
})
.catch(error => {
console.log(error);
});
}
render() {
return (
);
}
}
export default MyComponent;
在这个例子中,我们创建了一个React组件,该组件包含一个包含两个输入字段的表单。我们使用箭头函数来绑定handleInputChange和handleSubmit函数,这使得我们能够存储用户输入并在表单提交时将其发送到API。当使用 axios 发送 POST 请求时,我们可以使用.then()方法以及.catch()方法来处理响应或者错误信息。
使用上面的方法,我们可以在 React 项目中正确使用 axios 发起 post 请求。