【发布时间】:2016-05-19 23:36:29
【问题描述】:
您好,我在获取数据并将其作为 this.props.data 传递到子组件<GoogleMaps /> 并在数据更改时重新呈现时遇到问题。
它仅在第一次提交表单并获取数据时有效,但不再有效。新数据不可用,因为render() 函数在{this.renderData()} 之前调用{this.renderMap(this.props.data)},它获取并返回和映射数据。
我尝试切换它们,但看起来 render() 函数在调用 {this.renderMap(this.props.data)} 之前没有等到获取数据。我是否应该以不同的方式将数据传递给 GoogleMap 组件,以便在渲染之前重新加载新数据?
我的渲染数据();工作正常,返回组件ListItem。每次提交我的表单时它都会起作用。问题是让GoogleMaps 组件意识到这一变化并重新渲染?
class Feature extends Component {
handleFormSubmit({ term, location }) {
this.props.fetchData( { term, location });
this.setState({showMap: true});
}
renderData() {
return this.props.data.map((data) => {
return (
<ListItem
key={data.id}
data={data} />
)
});
}
renderMap(data) {
if (this.state.showMap == true) {
const lon = data[0].location.coordinate.longitude;
const lat = data[0].location.coordinate.latitude;
return (
<GoogleMap
data={data}
lon={lon}
lat={lat} />
)
}
}
render() {
const { handleSubmit, fields: { term, location }} = this.props;
return (
<div>
<div>
<form className="form-inline" onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
<fieldset className="form-group">
<label>Find:</label>
<input className="form-control" {...term} />
</fieldset>
<fieldset className="form-group">
<label>Location:</label>
<input className="form-control" {...location} />
</fieldset>
<button action="submit" className="btn btn-primary">Search</button>
</form>
</div>
<div className="map_container">
{this.renderMap(this.props.data)}
</div>
<ul className="list-group">
{this.renderData()}
</ul>
</div>
)
}
}
function mapStateToProps(state) {
return { data: state.data };
}
export default reduxForm({
form: 'search',
fields: ['term', 'location']
}, mapStateToProps, actions)(Feature);
这里是 fetchData 函数,我得到的数据很好。
export function fetchData( {term, location} ) {
return function(dispatch) {
axios.post(`${ROOT_URL}/data`, {term, location})
.then(response => {
dispatch({
type: FETCH_DATA,
payload: response
})
})
}
}
【问题讨论】:
-
你能告诉我们
fetchData()函数吗?
标签: javascript reactjs redux react-redux