当前我从API获取数据并将这些结果存储到数组中。这个问题,当我做数组映射到子组件时,它永远不会执行,因为数组是空的。如何在数组中包含数据时执行数组映射。我尝试内联条件,如{array.length> 0? //做数组映射}。我也尝试使数组成为全局数组和一个父组件状态的数组。使用数组映射在另一个组件中创建反应元素
//阵营路由器
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import Main from '../components/Main';
export default() => {
return <Route path="/" component={Main}/>
};
//主要成分
import React, { PropTypes, Component } from 'react';
// import bgImage from './ignasi_pattern_s.png';
import Child1 from './Children/Child1';
import axios from 'axios';
const QUERY_URL = "https://api.nytimes.com/svc/search/v2/articlesearch.json?api-key=";
//****Tried global array declaration and as a state property but both do not work.
// var articles = [];
class Main extends Component {
constructor(props){
super(props);
this.state = {
search: "",
articles: []
}
this.getTopic = this.getTopic.bind(this);
this.executeSearch = this.executeSearch.bind(this);
}
getTopic(event) {
this.setState({
search: event.target.value
});
}
executeSearch(event) {
event.preventDefault();
axios.get(QUERY_URL + "&q=" + this.state.search).then((response) => {
for(var i = 0; i < 5; i++){
this.state.articles.push({
headline: response.data.response.docs[i].lead_paragraph
})
}
});
}
render() {
return (
<div className="Main" style={{backgroundImage: `url(${"http://aiburn.com/files/articles/creating_professional_business_backgrounds/06.gif"})`}}>
<div className="page-header">
<h1>{getNiceName(this.props.routes)}{' '}
<small>page</small>
</h1>
<h1>Search For Something</h1>
<form onSubmit={this.executeSearch}>
<input type="text" value={this.state.search} onChange={this.getTopic}/>
<button type="submit" className="btn btn-default">Search</button>
</form>
</div>
<div className="container Main-content">
//Trouble here mapping the array to the child component.
//This never executes because the array is empty to begin with.
{this.state.articles.length > 0 ?
{this.state.articles.map((item, index) => {
return <Child1
key={index}
headline={item.headline}
/>;
})}
}
</div>
</div>
);
}
}
Main.propTypes = {
children: PropTypes.node,
routes: PropTypes.array
};
export default Main;
//子组件
import React, { Component } from 'react';
class Child1 extends Component {
constructor(props) {
super(props);
}
render() {
return <div>
<div className="container">
<h1>{this.props.headline}<span><button type="submit" className="btn btn-default">Save</button></span></h1>
</div>
</div>;
}
}
export default Child1;
好吧,即使阵列中有数据,它也不会显示任何内容。意思是子组件从来没有得到数组的索引 – henhen