ReactJS中如何将维基百科API返回的嵌套数组渲染为完整列表
问题根因
你当前的代码存在两个核心逻辑错误:
- 数据存储错误:维基百科opensearch接口返回的
res.data本身就是结构为[搜索关键词, 标题数组, 描述数组, 链接数组]的四元组,你额外给它套了一层数组存入result,导致result长度仅为1,遍历时只会执行一次。 - 遍历对象错误:你遍历的是外层的
result数组,而实际需要遍历的是返回结果中存储所有搜索结果标题的数组(四元组的第二个元素,索引为1)。
调整后的代码
1. 数据请求方法修改
fetchingData() { if (this.state.query === ''){ this.setState({result: []}) } else { const url = 'https://en.wikipedia.org/w/api.php?action=opensearch&origin=*&search=' + this.state.query; axios.get(url) .then(res => // 直接存储返回的原始四元组,无需额外包裹数组 this.setState({result: res.data})) } }
2. 渲染逻辑修改
<div> {/* 有返回结果时才渲染列表 */} {this.state.result.length > 0 && ( <ul> {/* 遍历标题数组渲染所有结果项 */} {this.state.result[1].map((title, index) => ( <li key={index}> <a href={this.state.result[3][index]} target="_blank" rel="noopener noreferrer" > {title} </a> </li> ))} </ul> )} </div>
注:这里用箭头函数替代普通函数,避免this指向问题,不需要额外绑定上下文。
内容的提问来源于stack exchange,提问作者Andrea
相关产品推荐
相关产品推荐

