2016-05-29 21 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 
      }); 
     }); 
    } 

這就是現在的作品!

相關問題