【发布时间】:2016-11-01 23:38:23
【问题描述】:
考虑到这个example
我是 React 的新手,所以这就是我创建新应用的方式
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")
);
计划是创建一个按钮,点击它会显示一个新的 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 正确地将新的 JSON 数据发布到渲染?
【问题讨论】:
-
请清理代码。这看起来像是 Babel 在 ES6 代码上的输出。如果有什么使用它,因为它很容易混淆你正在尝试做的事情。现在到底有什么问题?你心目中的“正确”是什么?如果这就是您的要求,那么在
componentDidMount中进行 ajax 调用是非常合理的 -
好吧,过去了,我看不出上面的代码有什么问题。怎么了?
-
同意@ZekeDroid 为什么不发布原始代码?如果你这样做,你会得到更好的帮助。
-
@azium 好的,谢谢,我更新了问题。
-
@ZekeDroid 谢谢,我用 Babel 代码更新了问题
标签: javascript ajax reactjs asynchronous http-post