问题
I'm a React JS newbie, I have this code that creates an app div with some MusicPlayer tag elements:
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
Let's say I want to replace the <MusicPlayer> with this:
<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>
How can this be done via Ajax?
回答1:
Use React's stateand setState to re-render the component with the new data. Call setState inside the ajax success callback and pass the new data to setState. This will render the MusicPlayer with the new data.
Hope this helps!
Pseudo code
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>
)
}
}
Ps. Frequency bars looks better than frequency ripples :P
来源:https://stackoverflow.com/questions/40357019/how-to-proper-use-ajax-in-react