在reactjs中从嵌套数组中创建列表



我正试图从维基百科API的结果列表,但我只能渲染数组中的第一个元素。

下面是一个响应示例和我的代码:

[" Dog";狗狗";狗肉";狗狗币";战争中的狗";狗狗品种";狗狗训练"狗狗标签"狗狗风格";狗狗宫殿";狗狗日Afternoon"]、[",",",",",",",",","],["https://en.wikipedia.org/wiki/Dog" https://en.wikipedia.org/wiki/Dog_meat"https://en.wikipedia.org/wiki/Dogecoin","https://en.wikipedia.org/wiki/Dogs_in_warfare","https://en.wikipedia.org/wiki/Dog_breed","https://en.wikipedia.org/wiki/Dog_training","https://en.wikipedia.org/wiki/Dog_tag"https://en.wikipedia.org/wiki/Doggystyle","https://en.wikipedia.org/wiki/Doge%27s_Palace","https://en.wikipedia.org/wiki/Dog_Day_Afternoon"]]

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]}))
}
}
<div>
{this.state.result.map(function(item, index){
return(
<ul>
<li><a href={item[3][index]} target="_blank" key={index}>{item[1][index]}</a></li>
</ul>
)
})}
</div>
Any idea on how I can show a list of all the results?

不要将res.data封装在数组中。改成{result: res.data}

import React from "react";
import { render } from "react-dom";
import axios from "axios";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
result: [],
query: ""
};
this.handleChange = this.handleChange.bind(this);
this.fetchingData = this.fetchingData.bind(this);
}
handleChange(e) {
this.setState({ query: e.target.value });
}
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 }));
}
}
componentDidMount() {
this.fetchingData();
setTimeout(() => {}, 200);
}
render() {
const key = this.state.result[1]; // name
const value = this.state.result[3]; // link
const mergedResults = key && key.map(function (x, i) {
return { result: x, link: value[i] };
})
return (
<div id="main">
<input
id="input"
placeholder="search"
value={this.state.query}
onChange={this.handleChange}
></input>
<button id="search" onClick={this.fetchingData}>
Search
</button>
<div>
<ul>
{mergedResults && mergedResults.map((item, i) => (
<li key={i}>
<a href={item.link}>{item.result}</a>
</li>
))}
</ul>
</div>
</div>
);
}
}
render(<App />, document.getElementById("root"));

这是我的解决方案,现场工作的例子在这里https://codesandbox.io/s/react-basic-class-component-forked-s0qoe

代码说明-我只是在这里映射结果数组1和3

const key = this.state.result[1]; // name
const value = this.state.result[3]; // link
const mergedResults = key && key.map(function (x, i) {
return { result: x, link: value[i] };
})

然后映射

<ul>
{mergedResults && mergedResults.map((item, i) => (
<li key={i}>
<a href={item.link}>{item.result}</a>
</li>
))}
</ul>

最新更新