我在React中创建了一个可过滤的表,并且我一直收到store.showFilteredResults.map is not a function
的错误。
我正在使用MobX来管理我的应用程序状态。这是商店:
class AppState {
@observable searchValue = "";
@observable donors = [
{id: 1, firstname: "John", lastname: "Smith", age: 43, contact: 7777777, type: 'O', rh: 'Positive'},
{id: 2, firstname: "Mary", lastname: "Smith", age: 25, contact: 7777447, type: 'AB', rh: 'Negative'}
]
@observable donorInfo = {
firstname: '',
lastname: '',
contact: '',
bloodType: 'A',
rhFactor: 'neg'
}
getSearchValue = (val) => this.searchValue = val
showFilteredResults () {
return this.donors.filter(donor => {
return donor.firstname.indexOf(this.searchValue) > -1
})
}
}
以下是我想根据用户输入过滤表格的组件:
@observer
class Search extends Component {
render(){
const store = this.props.store
const rhFilt = store.filterByRH
const btFilt = store.filterByBT
const filterType = rhFilt && btFilt ? <div><BloodTypeFilter/><RHFilter/></div>
: rhFilt ? <RHFilter/>
: btFilt ? <BloodTypeFilter/>
: null
const results = store.showFilteredResults.map( result => {
console.log(result)
})
return(
<div>
<form className="form-group">
<label htmlFor="filters">Filter by: </label>
{filterType}
<div className="filters-group">
<div className="filter-menu">
<label htmlFor="blood-type">Blood type</label>
<input
className="check"
type="checkbox"
value="bt"
onChange={this.handleSearchFilter}
/>
</div>
<div className="filter-menu">
<label htmlFor="rh-factor">Rh factor</label>
<input
className="check"
type="checkbox"
value="rh"
onChange={this.handleSearchFilter}
/>
</div>
</div>
<input
type="text"
className="form-control"
placeholder="search..."
value={store.searchValue}
onChange={this.getSearch}
/>
</form>
<div>
{store.showFilteredResults}
</div>
</div>
)
}
handleSearchFilter = (e) => {
const target = e.target.value
if (target==='bt')
this.props.store.searchByBT()
if (target==='rh')
this.props.store.searchByRH()
}
getSearch = (e) => {
this.props.store.getSearchValue(e.target.value)
}
}
export default Search
如何返回donor
数组,以便我可以使用输入字段对其进行过滤?
答案 0 :(得分:1)
您必须将showFilteredResults
变为computed:
@computed get showFilteredResults() {
return this.donors.filter(donor => {
return donor.firstname.indexOf(this.searchValue) > -1
})
}