我有一個特殊的問題。我目前正在學習 react 并從我自己的演示 API(一個 Java Spring 專案)中獲取資料。
但是,我在 React 中正確接收了資料。現在我正在用它創建組件(音樂曲目元資料)。API 的回應回傳一個物件陣列,物件中的一項是嵌套物件。現在我不知道如何將這些資訊提取到我的 React 組件中。
這是我的回應的示例 JSON:
Object {
??
duration: 200015
??
explicit: false
??
id: 8
??
isrc: "AUDCB1701705"
??
name: "Fireworks (feat. Moss Kena & The Knocks)"
??
songInfo: Object { id: 7, fullTitle: "Fireworks by Purple Disco Machine (Ft. The Knocks & Moss Kena)", geniusUrl: "https://genius.com/Purple-disco-machine-fireworks-lyrics", … }
???
fullTitle: "Fireworks by Purple Disco Machine (Ft. The Knocks & Moss Kena)"
???
geniusUrl: "https://genius.com/Purple-disco-machine-fireworks-lyrics"
???
id: 7
???
trackMetadata: null
如您所見,songInfo 是嵌套物件。我的反應組件是這樣的:
class ResultArea extends Component {
constructor(props) {
super(props);
this.state = {
tracks: []
}
}
componentDidMount() {
axios.get("http://localhost:8080/all")
.then(response => {
this.setState({
tracks: response.data
})
})
}
componentDidUpdate(prevProps, prevState, snapshot) {
console.log("Component updated! State is now:");
console.log(this.state.tracks);
}
render() {
const tracklist = this.state.tracks;
const tracks = tracklist.map(
({isrc, duration, explicit, fullTitle, geniusUrl}) =>
<Track key={isrc} fullTitle={fullTitle} isrc={isrc} duration={duration} explicit={explicit} geniusUrl={geniusUrl} />
);
return (
<React.Fragment>
<div className="border">
<ul>
{tracks}
</ul>
</div>
</React.Fragment>
)
}
}
我的組件的“狀態”保存了 API 請求的結果。這是如何運作的?我已經閱讀了一些關于嵌套物件的帖子,但我的方法是為每個軌道渲染一個“<Track ... /> 專案,因此帖子的建議方法對我不起作用......我需要“ GeniusUrl" 和嵌套的 songInfo-Object 中的 "fullTitle" 值...
非常感謝!
編輯:洗掉了評論。
uj5u.com熱心網友回復:
因此,您response.data是一組“曲目”。每個“軌道”都是一個物件。您目前正在像這樣在您的.map()方法中破壞您的“軌道” :
{isrc, duration, explicit, fullTitle, geniusUrl}
但是....fullTitle并且geniusUrl不是“跟蹤”物件的直接鍵,而是songInfo鍵,因此您必須調整解構:
{isrc, duration, explicit, songInfo: {fullTitle, geniusUrl}}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/337237.html
標籤:javascript 数组 反应 json 嵌套对象
上一篇:React表單提交和“無法對未安裝的組件執行狀態更新”?
下一篇:為新手創建反應函式
