【发布时间】:2018-04-19 22:16:03
【问题描述】:
我正在尝试使用 React,并且正在尝试创建一个搜索来过滤项目列表。我有两个组件,主要的一个显示调用 Search 组件的项目列表。
我有一个onChange 函数,它将状态中的term 设置为输入值,然后从主组件调用searchItems 以过滤项目列表。出于某种原因,在searchItems 中,this.state 是未定义的。我认为在 Search 组件中将 bind 添加到 onInputChange 可以解决问题,但没有任何区别。也许我缺少一些东西。
主要组件
import React, { Component } from 'react';
import _ from 'lodash';
import Search from './search';
class Items extends Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: []
};
}
componentDidMount() {
fetch("[url].json")
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result
});
}
),
(error) => {
this.setState({
isLoaded: true,
error
})
}
}
searchItems(term) {
const { items } = this.state;
const filtered = _.filter(items, function(item) {
return item.Name.indexOf(term) > -1;
});
this.setState({ items: filtered });
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
}
else if (!isLoaded) {
return <div>Loading...</div>;
}
else {
return (
<div>
<Search onSearch={this.searchItems}/>
<ul>
{items.map(item => (
<li key={item.GameId}>
{item.Name}
</li>
))}
</ul>
</div>
)
}
}
}
export default Items;
搜索组件
import React, { Component } from 'react';
class Search extends Component {
constructor(props) {
super(props);
this.state = {
term: ''
};
}
render() {
return (
<div>
<input type="text" placeholder="Search" value={this.state.term} onChange={event => this.onInputChange(event.target.value)} />
</div>
);
}
onInputChange(term) {
this.setState({ term });
this.props.onSearch(term);
}
}
export default Search;
【问题讨论】:
标签: javascript reactjs