[英]How to append data in React JS
I need to append this data response example in my React app. 我需要将此数据响应示例附加到我的React应用程序中。
DATA Response 数据响应
[
{
"trackInfo": {
"id": 1,
"title": "Guns & Dogs",
"artist": "Portugal, The Man",
"album": "The Satanic Satanist"
},
"trackUrl": "https://s3-us-west-2.amazonaws.com/teddarcuri.monarch/Portugal.+The+Man+-+Guns+%26+Dogs+-+The+Satanic+Satanist.mp3",
"albumArt": "http://ecx.images-amazon.com/images/I/61X7CiBpZ6L.jpg"
}
]
React JS React JS
class App extends React.Component {
constructor(props){
super(props)
this.state = { //initial empty details
details : {}
}
}
componentDidMount(){
//place the ajax call where ever you need
$.ajax() //call ajax
.done((data) => {
this.setState({ //this setState will re render the UI with the new state
details: { //change the key value pairs as needed
id: data.id,
trackInfo: {
title: data.title,
artist: data.artist,
album: data.album,
},
trackUrl: data.trackUrl,
albumArt: data.albumArt,
}
})
})
}
render() {
if(!this.state.details.id) return false //renders nothing when no details available
return (
<div id="app">
<MusicPlayer
id={this.state.details.id}
visualizerType="RIPPLES"
theme={darkTheme}
trackInfo={this.state.details.trackInfo}
trackUrl={this.state.details.trackUrl}
albumArt={this.state.details.albumArt}
utilities={true}>
</MusicPlayer>
</div>
)
}
}
ReactDOM.render(
<App />,
document.getElementById("app")
);
So my question is, how can I append the new data in React using Ajax? 所以我的问题是,如何使用Ajax在React中添加新数据?
A code example will be really appreciate, thanks. 一个代码示例将非常感谢,谢谢。
I think you want to show a list of MusicPlayer, so I changed your code: [you need to read more about state in react] 我认为您想显示MusicPlayer的列表,所以我更改了代码:[您需要阅读更多有关react状态的信息]
class App extends React.Component { constructor(props){ super(props) this.state = { //initial empty details details : [] // use array } } componentDidMount(){ //place the ajax call where ever you need $.ajax() //call ajax .done((data) => { let array = this.state.details; array = [...array, { id: data.id, trackInfo: { title: data.title, artist: data.artist, album: data.album, }, trackUrl: data.trackUrl, albumArt: data.albumArt, }]; this.setState({ details: array }) }) } render() { if(!this.state.details.id) return false //renders nothing when no details available return ( <div id="app"> { this.state.details.map((detail) => { return <MusicPlayer id={detail.id} visualizerType="RIPPLES" theme={darkTheme} trackInfo={detail.trackInfo} trackUrl={detail.trackUrl} albumArt={detail.albumArt} utilities={true}> </MusicPlayer> }); } </div> ) } } ReactDOM.render( <App />, document.getElementById("app") );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.