如何使用ReactJS从指定URL获取JSON数据?
修复说明
核心问题点
- 请求URL参数存在HTML转义错误:代码中使用的
&是HTML场景下的转义字符,在JS代码中直接使用会导致format=json参数无法被接口正确识别,需要替换为原生的&符号 - 接口返回结构与预期不匹配:你调用的SoundCloud oembed接口返回的是单条音频资源的元数据对象,不存在你代码中预设的
member数组、name/age这类字段 - setState操作不符合state定义:你直接执行
this.setState(res.data)会把整个state替换为接口返回的对象,原定义的member字段会被直接覆盖丢失 - 可能存在跨域限制:SoundCloud的oembed接口默认未开放CORS跨域权限,直接通过axios发起请求会触发浏览器跨域拦截,可改用jsonp请求或者代理中转解决
修正后可运行代码
import React from "react"; import { render } from "react-dom"; import axios from "axios"; // 如果遇到跨域问题,可安装fetch-jsonp依赖替换axios:import fetchJsonp from 'fetch-jsonp' class App extends React.Component { constructor() { super(); this.state = { // 保留原有member字段,可适配你后续其他业务接口 member: [], // 新增字段存储SoundCloud接口返回数据 soundcloudMeta: null }; } // 原有member列表渲染逻辑保留 memberList(list) { const memberList = list.map((member, index) => { return ( <li key={index}> {member.name} {member.age} </li> ); }); return <ul>{memberList}</ul>; } // 新增SoundCloud元数据渲染逻辑 renderSoundcloudMeta() { if (!this.state.soundcloudMeta) return null; const { title, author_name, thumbnail_url, html } = this.state.soundcloudMeta; return ( <div className="soundcloud-card"> <h3>音频信息</h3> <img src={thumbnail_url} alt={title} style={{ width: 200 }} /> <p>标题:{title}</p> <p>作者:{author_name}</p> {/* 若要嵌入播放器可直接使用返回的html字段 */} <div dangerouslySetInnerHTML={{ __html: html }} /> </div> ) } render() { return ( <div> <button onClick={this.getJson}>获取JSON数据</button> {/* 原有member列表渲染,若不需要可注释 */} {/* {this.memberList(this.state.member)} */} {this.renderSoundcloudMeta()} </div> ); } getJson = () => { // 修正URL中的转义字符 const url = "https://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=json"; axios.get(url) .then((res) => { // 仅更新对应state字段,不覆盖整个state this.setState({ soundcloudMeta: res.data }); }) .catch(err => { console.log('跨域请求被拦截,可改用jsonp方案:', err); // 启用以下代码使用jsonp请求,需要先安装fetch-jsonp依赖 // fetchJsonp(url) // .then(res => res.json()) // .then(data => this.setState({ soundcloudMeta: data })) }); }; } render(<App />, document.getElementById("root"));
如果你只是想测试member列表的渲染逻辑,替换成返回对应member数组结构的接口即可。
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

