Javascript 如何在React中正确使用Ajax
我是一名React JS新手,我有一段代码,可以创建一个带有一些标签元素的Javascript 如何在React中正确使用Ajax,javascript,ajax,reactjs,Javascript,Ajax,Reactjs,我是一名React JS新手,我有一段代码,可以创建一个带有一些标签元素的appdiv: class App extends React.Component { render() { return ( <div id="app"> <MusicPlayer id="2" visualizerType="RIPPLES"
app
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")
);
类应用程序扩展了React.Component{
render(){
返回(
)
}
}
ReactDOM.render(
假设我想用以下内容替换
:
<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实现这一点?使用React的状态
和设置状态
使用新数据重新呈现组件。在Ajax成功回调中调用设置状态
,并将新数据传递给设置状态
。这将使用新数据呈现音乐层
希望这有帮助
伪码
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>
)
}
}
类应用程序扩展了React.Component{
建造师(道具){
超级(道具)
this.state={//初始空详细信息
详细信息:{}
}
}
componentDidMount(){
//将ajax调用放在需要的地方
$.ajax()//调用ajax
.完成((数据)=>{
this.setState({//this setState将使用新状态重新呈现UI
详细信息:{//根据需要更改键值对
id:data.id,
轨道信息:{
标题:data.title,
艺术家:data.artist,
相册:data.album,
},
trackUrl:data.trackUrl,
albumArt:data.albumArt,
}
})
})
}
render(){
如果(!this.state.details.id)返回false//则在没有可用详细信息时不会呈现任何内容
返回(
)
}
}
Ps.频率条看起来比频率涟漪好:p你能详细说明一下吗?@PraneshRavi我需要了解如何删除MusicPlayer并通过post Ajax添加一个新的。我不清楚渲染后如何继续。新的是什么意思?另一个MusicPlayer?@PraneshRavi是的,MusicPlayer是一个音乐播放器卡,我会I’我想在单击更改时将其更改为什么?@SimonLeCat没有问题。我真的很喜欢频率栏。祝你好运!我认为你的代码有问题(未知:意外标记),请仔细检查details={}
@SimonLeCat这是一个很好的问题。这应该有助于您理解jQuery。如果您需要进一步的帮助,您可以提出一个新的问题,标记jQuery.Yes。一个包含所有必需信息的JSON