我有一个React应用程序在其中,我必须调用一个API。 我创建了一个dataservice.js
,我将在其中创建调用API的所有函数。
在我需要检索数据的组件中,我只是尝试console.log数据,但是我有一个承诺{
,而不是我需要的结果。。。 我可以做什么来检索数据?
我最初的想法是使用这个dataservice.js
检索我需要的所有数据,并用数据设置组件的状态。 我想这是可能的,但怎么可能呢?
dataservice.js:
export const dataService = {dataValue};
function dataValue() {
return axios.get('url/to/api')
.then(response => {
console.log(response.data.soc) //this works well !
let soc = response.data.soc
return soc;
});
}
myComponent.js:
class myComponent extends Component {
render() {
let test = dataService/dataValue(); // I imported the dataService !
console.log(test);
return (<div></div>);
}
}
首先,我建议使用React钩子,结合使用/函数组件来检索数据。 像这样的东西:
myComponent.js
import React, {useEffect, useState} from 'react';
import axios from 'axios';
const MyComponent = () => {
const [data, setData] = useState([]);
useEffect(() => {
axios.get('url/to/api')
.then(response => {
setData(response);
});
}, []);
return (<div>{data.map(d => <<DO WHATEVER YOU WANT W/ DATA HERE>>)}</div>);
}
发出API请求是异步的。 所以这里需要一个异步函数
const dataValue = async () => {
const response = await axios.get('url/to/api');
return response.data.soc;
}