2016-11-01 59 views
3

我是一个阵营JS新手,我有这样的代码创建一个app DIV一些MusicPlayer标签元素:如何正确使用Ajax的阵营

class App extends React.Component { 
    render() { 
     return (
      <div id="app"> 
       <MusicPlayer 
        id="2" 
        visualizerType="RIPPLES" 
        theme={darkTheme} 
        trackInfo={{ 
         title: "Imitosis", 
          artist: "Andrew Bird", 
           album: "Armchair Apocrypha" 
        }} 
        trackUrl="https://s3-us-west-2.amazonaws.com/teddarcuri.monarch/Andrew+Bird+-+Imitosis.mp3" 
        albumArt="https://s3-us-west-2.amazonaws.com/teddarcuri.monarch/andrew+bird.jpg" 
        utilities={true}> 
       </MusicPlayer> 
      </div> 
     ) 
    } 
} 

ReactDOM.render(
    <App />, 
    document.getElementById("app") 
); 

UPDATE

Based on this pen

比方说,我想用此代替<MusicPlayer>

<MusicPlayer 
    id="3" 
    visualizerType="RIPPLES" 
    theme={lightTheme} 
    trackInfo={{ 
     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" 
    utilities={true}> 
</MusicPlayer> 

这怎么能通过Ajax完成?

+0

你能详细说明一下吗? –

+0

@PraneshRavi我需要了解如何删除MusicPlayer并通过发布Ajax添加新的。我不清楚如何在渲染后继续。 – NineCattoRules

+0

**新人**是什么意思?另一个MusicPlayer? –

回答

2

使用React的statesetState重新渲染具有新数据的组件。在ajax成功回调中调用setState,并将新数据传递给setState。这将使新数据呈现MusicPlayer

希望这会有所帮助!

伪代码

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> 
     ) 
    } 
} 

诗篇。频率棒看起来比频率波纹好:P

+1

@SimonLeCat没问题。我非常喜欢频率条。祝你好运! –

+0

我认为你的代码存在问题(未知:意外的代币),请仔细检查'details = {} – NineCattoRules

+1

@SimonLeCat更新了它!谢谢 –