Javascript 将API JSON结果传播为选项列表
我正在react中构建一个简单的新闻应用程序。 我正在从newsapi.org获取API,并试图在我的选择组件的列表中显示新闻源选项 但是,它目前将每个新闻源显示为一个新的单独选项,而不是将其全部列在一个选项组件中。 (如果这很难理解,很抱歉,英语不是我的第一语言。因此,我在代码中包含了截图) 提前谢谢大家Javascript 将API JSON结果传播为选项列表,javascript,json,reactjs,api,Javascript,Json,Reactjs,Api,我正在react中构建一个简单的新闻应用程序。 我正在从newsapi.org获取API,并试图在我的选择组件的列表中显示新闻源选项 但是,它目前将每个新闻源显示为一个新的单独选项,而不是将其全部列在一个选项组件中。 (如果这很难理解,很抱歉,英语不是我的第一语言。因此,我在代码中包含了截图) 提前谢谢大家 componentDidMount() { fetch('http://beta.newsapi.org/v2/sources?apiKey=XXX') .then(resu
componentDidMount() {
fetch('http://beta.newsapi.org/v2/sources?apiKey=XXX')
.then(results => {
return results.json();
}).then(data => {
let sources = data.sources.map((src) => {
return(
<div key={src.sources}>
<select className="form-control form-inline">
<option value={src.id}>{src.name}</option>
</select>
</div>
)
})
this.setState({sources: sources});
})
}
render() {
return(
<div className="container">
<h2>Select a news source:</h2>
{this.state.sources}
</div>
)
}
}
componentDidMount(){
取('http://beta.newsapi.org/v2/sources?apiKey=XXX')
。然后(结果=>{
返回results.json();
})。然后(数据=>{
让sources=data.sources.map((src)=>{
返回(
{src.name}
)
})
this.setState({sources:sources});
})
}
render(){
返回(
选择新闻来源:
{this.state.sources}
)
}
}
我看到@char已经为您解决了这个问题。不过,代码还是在这里。 另外,更好的做法是只存储状态中的“数据”,然后使用状态在“render”函数中渲染视图
class MyComponent extends React.Component {
//other code
componentDidMount() {
fetch('http://beta.newsapi.org/v2/sources?apiKey=XXX')
.then(results => {
return results.json();
}).then(data => {
this.setState({sources: data.sources});
})
}
render() {
return(
<div className="container">
<h2>Select a news source:</h2>
<SelectComponent sources={this.state.sources} />
</div>
)
}
}
const SelectComponent = ({sources})=>(
<select className="form-control form-inline">
{sources.map((source)=>
<option value={source.id} key={source.id} > {source.name} </option>
)}
</select>
);
类MyComponent扩展了React.Component{
//其他代码
componentDidMount(){
取('http://beta.newsapi.org/v2/sources?apiKey=XXX')
。然后(结果=>{
返回results.json();
})。然后(数据=>{
this.setState({sources:data.sources});
})
}
render(){
返回(
选择新闻来源:
)
}
}
const SelectComponent=({sources})=>(
{sources.map((source)=>
{source.name}
)}
);
映射应返回单个
选项
s,嵌套在父项下选择
。您当前映射它的方式返回单个选项
元素及其自己的选择
元素。@char抱歉,我不太明白。对javascript来说,这是一个全新的概念。如果您不介意的话,您可以对此进行一点扩展吗?对于data.sources
中的每个元素,您将返回。最终结果是多个选择/选项元素。你想要的是……@char完美的解释!我通过在渲染方法中修复它来修复它。再次感谢你!