如何在React中正确使用Ajax

时间:2016-11-01 09:12:02

标签: javascript ajax reactjs

我是React JS的新手,我有这个代码创建一个带有app个标记元素的MusicPlayer div:

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")
);

更新

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完成?

1 个答案:

答案 0 :(得分: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