如何解决导出具有导入的axios响应数据的函数 api.js import.js importCars.js
目前,我有两个文件,一个用于获取和获取数据响应。另一个js文件是将这些结果导入函数中。我想导出最后一个函数,以便可以在其他文件中使用它。
api.js
import axios from 'axios';
const url = 'data/data.json';
const cars = 'data/cars.json';
export const fetchData = () => {
return axios.get(url)
.then(response => {
return response.data
})
}
export const fetchCars = () => {
return axios.get(cars)
.then(response => {
return response.data
})
}
import.js
请参阅:export const details
import { fetchData,fetchCars } from './api';
let fetchingData = fetchData();
let fetchingCars = fetchCars();
// I want to export the below functionality:
fetchingData.then((result) => {
// I will be doing stuff here
console.log(result);
})
export const details = () => {
fetchingCars.then((result) => {
// I will be doing stuff here
console.log(result);
})
}
// And be able to console.log the results out of that exported function. Since I will need to update DOM values based on the API results.
console.log(details);
importCars.js
import { details } from './import'
function example() {
// do something
details();
}
解决方法
只需如下更改api.js中的fetchData,
export const fetchData = () => {
return axios.get(url)
}
在import.js中,如下所示进行记录时,请使用result.data
而不是result
fetchingData.then((result) => {
// I will be doing stuff here
console.log(result.data);
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。