我有一个包含此数据分支的API
{
"data": {
"id": ,
"title": ,
"description": ,
"old_price": "100",
"new_price": "50",
"size": "50",
"quantity": 20,
},
"errors": null,
"code": 1
}
我使用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'));
我在这里渲染
import React from 'react';
export default class Layout extends React.Component{
render(){
let data = this.props.data;
return (
<div>
{data.name}
</div>
)
}
}
但是没有渲染,我想我的做法是错误的。请你帮帮我。
答案 0 :(得分:2)
const title=response.body.response
应该是
const title=response.body
最有可能
答案 1 :(得分:1)
对我来说,这样的事情正在发挥作用:
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
};
}