我想讓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