作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
这是一个运行良好的典型容器组件:
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 组件中。
所以我在项目的 api
文件夹中创建了一个 profiles.js
文件:
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
链接,因为 fetch api 返回 res.json()
作为 promise 。
我尝试将 fetchProfiles
包装在一个外部函数中,也在一个新的 promise 中!但是没有任何效果!我在这里做错了什么?请帮助进行此重构。
最佳答案
你需要返回 fetch(url)
本身,所以你会返回一个 promise ,然后你可以使用 then
方法:
const API = 'https://randomuser.me/api/?results=5';
export function fetchProfiles() {
let url = API;
// return the promise itself
return fetch(url).then( (res) => res.json() );
}
关于javascript - react : How do I move my ajax api call into a separate component?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37509813/
我是一名优秀的程序员,十分优秀!