2016-10-24 45 views
0

我有一個API,其中title, description, old pricenew price應呈現,但我不知道如何正確的方式。在react.js中使用API​​呈現數據?

與我的API

export class Content extends React.Component{ 
    constructor(){ 
     super(); 
     this.state={}; 
    } 
    componentWillMount(){ 
     var url="95.85.23.63:8000/frontend/web/api/v1/user/get-popular"; 
     Request.get(url).then((reponse)=>{ 
      this.setState({ 
       infos:response.body.Search, 
       total:response.body.totalResults 
      }); 
     }); 
    } 

    render(){ 
     var infos=_.map(this.state.infos, (info)=>{ 
      return <li>{info.title}</li>; 
     }); 

     return(
     <div> 
     <ul> {infos}</ul> 

     </div> 
     ) 
    } 

} 

下面內容組成部分我覺得我在一個錯誤的方式檢索數據。你可以幫我嗎?

+0

您應該創建動作,然後要麼你可以使用反應-thunk或react-saga從api中檢索數據。當組件裝入時,意味着componentDidMount(){this.props.dispatch(search())} –

回答

0

你正在和async打電話。所以,你需要處理渲染中的空狀態。請看下面的代碼

[編輯]

正如在評論中提到,建議向請求componentDidMount()

export class Content extends React.Component{ 
    constructor(){ 
     super(); 
     this.state={ 
      infos: [], 
      total: 0, 
     }; 
    } 
    componentDidMount(){ 
     var url="95.85.23.63:8000/frontend/web/api/v1/user/get-popular"; 
     Request.get(url).then((reponse)=>{ 
      this.setState({ 
       infos:response.body.Search, 
       total:response.body.totalResults 
      }); 
     }); 
    } 

    render(){ 
     if(this.state.infos.length === 0) 
      return false //return false when nothing is in the state 
     var infos=_.map(this.state.infos, (info)=>{ 
      return <li>{info.title}</li>; 
     }); 

     return(
     <div> 
     <ul> {infos}</ul> 

     </div> 
     ) 
    } 

} 
+0

我認爲我們不應該在componentwillMount中做ajax請求,它可能觸發無限循環並可能阻止組件安裝。我們應該寫在componentdidMount –

+0

這不是事實。你不應該在'componentDidUpdate'上設置狀態。這將導致無限循環。希望這清除你的疑問。 –

+0

檢查此問題http://stackoverflow.com/questions/27139366/why-do-the-react-docs-recommend-doing-ajax-in-componentdidmount-not-componentwi –