jb0*_*b07 0 javascript reactjs axios
我正在开发一个React应用程序,该应用程序使用导入的对象以及对api的获取请求和对相关API的发布请求。
在React的前端中创建服务的新实例时,我能够成功地使用'.then'和'.catch'函数来仅从get请求访问返回的数据。
当使用来自同一对象的发布请求时,尝试访问响应对象时,我得到了(反义)“。then”,它不是未定义的函数。
只有当我在表单提交功能中显式写出发布请求(不使用服务)并处理对象时,我才能检查响应并随后设置状态。
在React中使用axios的适当/最佳实践方法是什么?为什么在创建服务的新实例时不能访问响应对象?非常感激!
服务:
import axios from 'axios';
class ProductServices {
getAllProducts(){
return axios.get('https://somecustomAPIURL')
}
postProduct(somePathConfig){
axios.request({
url: 'https://somecustomAPIURL' + somePathConfig,
method: 'post',
headers: {'some-custom-header': process.env.REACT_APP_API_POST_KEY}
})
}
}
export default ProductServices;
Run Code Online (Sandbox Code Playgroud)
React Code instantiating and consuming the service (note, that getAllProducts works just fine, but trying to consume a response object in postProduct returns an '.then' is undefined)
constructor(){
super();
this.state = {
products: [],
productID: null,
showModal: false
}
this.ProductServices = new ProductServices();
}
getAllProducts = () => {
this.ProductServices.getAllProducts()
.then((response) => {
let items = response.data.data.items;
this.setState({
products: items,
productID: items[0].id
});
return response;
})
.catch((error) => {
console.log('Error!', error);
return error;
})
}
handleFormSubmit = (e) => {
e.preventDefault();
let productID = this.state.productID;
this.ProductServices.postProduct(productID)
.then((response) => {
this.setState({showModal: true}, () => console.log('Success!'));
return response;
})
.catch((err) => {
console.log('Error!', err);
})
}
Run Code Online (Sandbox Code Playgroud)
你return以前错过了axios.request。
import axios from 'axios';
class ProductServices {
...
postProduct(somePathConfig){
return axios.request({
url: 'https://somecustomAPIURL' + somePathConfig,
method: 'post',
headers: {'some-custom-header': process.env.REACT_APP_API_POST_KEY}
})
}
...
Run Code Online (Sandbox Code Playgroud)
另外,除了,axios.request您还可以使用axios.postlikeaxios.get
return axios.post(url, body, { headers });
return axios.get(url, { headers });
return axios.put(url, body, { headers });
return axios.delete(url, { headers });
return axios.request(axiosConfigOptions);
Run Code Online (Sandbox Code Playgroud)