2016-05-29 19 views
0

这里是工作得很好典型的容器组件:反应:如何将我的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在一个外部函数中,在一个新的承诺呢!但没有任何作品!我在这里做错了什么?请帮助这个重构。

+1

您需要返回'取(URL)'本身,所以你会返回一个承诺,然后你可以使用'then'方法。 –

回答

4

您需要返回fetch(url)本身,所以你会返回一个承诺,那么你可以使用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()); 
} 
0

我解决了这个问题的办法是返回fetch(url)本身:

const API = 'https://randomuser.me/api/?results=5'; 

export function fetchProfiles() { 
    let url = API; 
    return fetch(url) 
     .then((response) => response.json()); 
} 

然后在容器组件:

componentDidMount() { 
     fetchProfiles() 
     .then((data) => { 
      let results = data.results; 
      this.setState({ 
      profiles: results 
      }); 
     }); 
    } 

这就是现在的作品!

相关问题