簡體   English   中英

如何在React JS中追加數據

[英]How to append data in React JS

我需要將此數據響應示例附加到我的React應用程序中。

數據響應

[
  {
    "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

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")
);
  • 完整的代碼示例在這里
  • 此處帶有預加載數據的工作示例

所以我的問題是,如何使用Ajax在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM