【发布时间】:2017-10-28 15:38:22
【问题描述】:
我正在尝试构建一个项目,只是为了让自己熟悉 React 和 redux 。 我有一个来自 Json (axios.get) 的数据,其中包含数据,并且我正在使用该数据构建一个表。
到目前为止一切顺利,因为数据完美地显示在表格上,但我将在页面顶部放置一个搜索输入,所以当用户尝试搜索特定国家、首都、地区等时,该表格应该更新.所以简而言之,我试图实现THIS
到目前为止,我有以下代码
组件
import _ from 'lodash';
import React, {Component} from 'react';
import { connect } from 'react-redux';
import { fetchCountries } from '../actions';
import SearchBar from './search_bar';
class FetchCountries extends Component {
constructor(props){
super(props);
this.state = {searchValue : ''}
}
componentDidMount(){
this.props.fetchCountries();
}
renderCountries() {
const { countries } = this.props;
return _.map(countries , country =>{
return (
<tr key={country.name.official}>
<td> {country.name.official} </td>
<td> {country.capital} </td>
<td> {country.region} </td>
<td> {country.subregion} </td>
</tr>
);
});
}
这是我想要实现的功能
handleSearchTerm(event) {
// this should return value in the table by comparing value in the table and user input
}
render() {
return(
<div>
<SearchBar onSearchTermChange= { this.handleSearchTerm }/>
<table className="table table-hover">
<thead className="thead-dark">
<tr>
<th scope="col">Countries</th>
<th scope="col">Capital</th>
<th scope="col">Region</th>
<th scope="col">SubRegion</th>
</tr>
</thead>
<tbody>
{this.renderCountries()}
</tbody>
</table>
</div>);
}
}
function mapStateToProps (state) {
return { countries: state.countries };
}
export default connect (mapStateToProps, { fetchCountries })(FetchCountries);
search_bar.js
import React, { Component } from 'react';
class SearchBar extends Component {
constructor(props){
super(props);
this.state = { term: ''}
this.handleChange = this.handleChange.bind(this);
}
handleChange (term) {
this.setState({term});
this.props.onSearchTermChange(term);
}
render() {
return (<input value={this.state.term} onChange= {event => this.handleChange(event.target.value)}/>);
}
}
ras
export default SearchBar;
reducer.js
import _ from 'lodash';
import { FETCH_COUNTRIES } from '../actions';
export default function (state = {} , action) {
switch(action.type){
case FETCH_COUNTRIES:
return _.mapKeys(action.payload.data, 'name.official');
default:
return state;
}
}
任何帮助都会得到满足!!
【问题讨论】:
标签: reactjs redux react-redux