【发布时间】:2016-09-27 08:20:54
【问题描述】:
这是一个运行良好的典型容器组件:
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() 作为承诺。
我尝试将fetchProfiles 包装在一个外部函数中,也包括在一个新的承诺中!但没有任何效果!!我在这里做错了什么?请帮助进行此重构。
【问题讨论】:
-
你需要自己返回
fetch(url),所以你会返回一个promise,然后你就可以使用then方法了。
标签: javascript ajax api reactjs refactoring