我想让React从Django Rest Framework API获取JSON。链接是这样写这样http://127.0.0.1:8000/band/api/1/?format=json和结构如下:从React调用API
{
id: 1,
name: "Muse",
date_added: "2017-04-17",
image: "https://upload.wikimedia.org/wikipedia/commons/a/a3/Muse_melbourne28012010.jpg",
bio: "Muse are an English rock band from Teignmouth, Devon, formed in 1994. The band consists of Matt Bellamy (lead vocals, guitar, piano, keyboards), Chris Wolstenholme (bass guitar, backing vocals, keyboards) and Dominic Howard (drums, percussion)."
}
我反应过来是这样写这样:
class ItemLister extends React.Component {
constructor() {
super();
this.state={items:[]};
}
componentDidMount(){
fetch(`http://127.0.0.1:8000/band/api/1/?format=json`)
.then(result=>result.json())
.then(items=>this.setState({items}))
setTimeout(() => console.log(this.state.items), 2000)
}
render() {
return(
<ul>
{this.state.items.length ?
this.state.items.map(item=><li key={item.id}>{item.name}</li>)
: <li>Loading...</li>
}
</ul>
)
}
}
ReactDOM.render(
<ItemLister />,
document.getElementById('container')
);
的HTML div容器停留在载入中...,控制台显示没有错误。我知道它与JSON有关,但无法弄清楚它是什么,任何帮助表示赞赏!
编辑:
添加如下面之后通过建议m_callens:
的setTimeout(()=>的console.log(this.state.items),2000)
控制台返回我确实想要获取的对象,但它仍然不会在页面上呈现。
Object {id: 1, name: "Muse", date_added: "2017-04-17", image: "https://upload.wikimedia.org/wikipedia/commons/a/a3/Muse_melbourne28012010.jpg", bio: "Muse are an English rock band from Teignmouth, Dev…eyboards) and Dominic Howard (drums, percussion)."}
你真的获得数据吗?尝试注销第二个项目。然后 – WilomGfx
@WilomGfx我加了console.log(this.items)在第二个.then下面,它说undefined。 – NewScientists
那么你没有收到API的数据,确保它在服务器端工作。 – WilomGfx