2016-11-08 48 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 
    }; 
}