这里是工作得很好典型的容器组件:反应:如何将我的ajax api调用移动到单独的组件中?
const API = 'https://randomuser.me/api/?results=5';
class App extends Component {
constructor(props) {
super(props);
this.state = { profiles: [] };
}
componentDidMount() {
this.fetchProfiles();
}
fetchProfiles() {
let url = API;
fetch(url)
.then((res) => res.json())
.then((data) => {
let results = data.results;
this.setState({
profiles: results
});
})
.catch((error) => console.log('Oops! . There Is A Problem', error));
}
render() {
// rendering child component here
}
}
export default App;
什么我想现在要做的就是移动fetchProfiles
功能到一个单独的API组件。
所以我做一个profiles.js
文件中的一个api
文件夹在我的项目:
const API = 'https://randomuser.me/api/?results=5';
export function fetchProfiles() {
let url = API;
fetch(url)
.then((res) => res.json());
}
现在我的主要组成部分进口它并使用它,像这样:
import { fetchProfiles } from '../api/profiles.js';
const API = 'https://randomuser.me/api/?results=5';
class App extends Component {
constructor(props) {
super(props);
this.state = { profiles: [] };
}
componentDidMount() {
fetchProfiles.then((data) => {
let results = data.results;
this.setState({
profiles: results
});
});
}
// render call etc
但是当我运行请拨打componentDidMount
这样,我得到这个错误:Uncaught TypeError: _profiles.fetchProfiles.then is not a function
。我试图链接then
,因为提取api返回res.json()
作为承诺。
我试穿了fetchProfiles
在一个外部函数中,在一个新的承诺呢!但没有任何作品!我在这里做错了什么?请帮助这个重构。
您需要返回'取(URL)'本身,所以你会返回一个承诺,然后你可以使用'then'方法。 –