【发布时间】:2018-09-27 03:53:53
【问题描述】:
我正在使用 react,我的目标是通过调用从 spotify api 获取 url 的函数将特定的 url 放入 href 中。函数如下所示:
<a href={Spotify.getPreviewUrl(this.props.track.ID).then(results => {
console.log(results);
return results;
})}>Track Preview</a>
然后调用一个从 Spotify api 获取 Url 的函数
getPreviewUrl(trackId) {
return fetch(`https://api.spotify.com/v1/tracks/${trackId}`, {
headers: {
Authorization: `Bearer ${usersAccessToken}`
}
}).then(response =>
response.json()).then(jsonResponse => {
console.log(jsonResponse);
return jsonResponse.preview_url;
});
}
现在回到我最初的通话中:
<a href={Spotify.getPreviewUrl(this.props.track.ID).then(results => {
console.log(results);
return results;
})}>Track Preview</a>
console.log() 值正是我想要的 url,但它并没有像我想要的那样成为 href url 地址,即使我返回了那个值。有谁知道我怎样才能让这个值成为实际的 href url?
【问题讨论】:
-
您正在尝试异步设置属性 - console.log 正确的原因是因为它在
getPreviewUrl解析后正确 - 但您不能设置这样的属性 -
你希望
<a href={this.state.previewURL}>与componentDidMount() { Spotify.[.....].then(respone => this.setState({ previewURL: response.preview_url })配对,这样 react 就可以简单地做它应该做的事情:根据 state/props 更新来更新你的 UI。
标签: javascript json reactjs api fetch