2016-11-08 46 views
-2

我有一個包含數據使用superagent調用API?

{ 
 
    "data": { 
 
    "id": , 
 
    "title": , 
 
    "description": , 
 
    "old_price": "100", 
 
    "new_price": "50", 
 
    "size": "50", 
 
    "quantity": 20, 
 
    }, 
 
    "errors": null, 
 
    "code": 1 
 
}

我爲了調用API,並展示這個信息將SuperAgent的這個分支的API,但我在錯誤的方式這樣做。

這裏我的代碼

import React from 'react'; 
 
import {render} from 'react-dom'; 
 
import superagent from 'superagent'; 
 
import Layout from './components/Layout'; 
 

 
class App extends React.Component{ 
 
    constructor(){ 
 
    super() 
 
    this.state={ 
 
     name:'' 
 
    } 
 
    } 
 
    componentDidMount(){ 
 
     console.log('componentDidMount'); 
 

 
     const url='http://...'; 
 
     superagent 
 
     .get(url) 
 
     .query(null) 
 
     .set('Accept', 'application/json') 
 
     .end ((error, response)=>{ 
 
      const title=response.body.response 
 
      console.log(JSON.stringify(title)); 
 
      
 
      this.setState({ 
 
       name:title 
 
      }) 
 
     }) 
 
     
 
    } 
 
    render(){ 
 
    return(
 
     <Layout data={this.state}/> 
 
    ) 
 
    } 
 
} 
 

 

 
render(<App />, document.getElementById('app'));

在這裏,我使其

​​

但不渲染,我想我的錯誤行爲W¯¯唉。請你能幫我解決這個問題。

回答

2
const title=response.body.response 

應該

const title=response.body 

最有可能

+0

嘿,感謝ü它的工作!當然,我做了一些調整,但這是一個起點) – Feruza

0

對我來說是這樣的工作:

import request from 'superagent'; 

getFooFromServer() { 
    const url='http://...'; 
    request.get(`${url}/foo`) 
    .accept('json') 
    .then(res => { 
     //Do something with your data 
    } 
    catch(error => { 
     //Do something with the error 
    }; 
}