reactjs - 在反应中使用客户端搜索
问题描述
搜索功能在控制台日志中运行良好,但是当我尝试将该值分配给作为状态的行时。所以我在searchHandler中setState里面的行setState。我知道我犯了一个错误,但我不知道如何纠正它。省略未声明的状态,将代码缩小到所需的内容
function searchingFor(searchingTerm) {
return function(x){
// console.log("searching",x);
return x.name.toLowerCase().includes(searchingTerm.toLowerCase())|| false;
}
}
class Main extends React.Component{
componentWillMount(){
this.props.fetchTopicsTableContent(this.state.sortBy,'ASC',0,this.props.match.params.CategoryName).then(result=> (this.setState({rows:result.payload.data})))
this.props.countTableContent(this.props.match.params.CategoryName).then(result=>(this.setState({count:result.payload})));
}
constructor(props){
super(props);
this.state={
rows:"",
searchTerm:"",
items:""
}
}
onSubmit(values){
values.preventDefault();
}
onSearchHandler(e){
this.setState({searchTerm:e.target.value},()=>{
{this.state.rows.filter(searchingFor(this.state.searchTerm)).map(item=>{
console.log(item);
//this.setState({rows:item})
})}
})
}
render(){
return(
<div>
<h3>Topics</h3>
<hr/>
<div>
<form onSubmit={this.onSubmit.bind(this)}>
<input type="text"
className="searchBar"
value={this.state.searchTerm}
onChange={this.onSearchHandler.bind(this)}
/>
</form>
</div>
</div>
)
}
解决方案
好的,让我们从在构造函数中绑定你的函数开始,而不是在标记中,清理东西:P
接下来,我不确定您是否了解设置状态是如何工作的,因为您的功能违背了它的基本用途。您正确设置了第一个状态并使用了回调(因为实际设置状态需要时间),这很棒。回调函数是它走下坡路的地方。
您的映射函数会立即加载多个 setState 调用,每个调用 console.log() 都会成功运行,但实际上只有一个 setState 会生效。最重要的是,即使它确实有效,您的rows
状态也只会有一个项目。让我们试试这个:
onSearchHandler(e){
this.setState(prevState => {
return {
rows: prevState.rows.filter(searchingFor(e.target.value)),
searchTerm: e.target.value,
}
});
}
这会让你得到我认为是想要的结果......你应该一次只做一个 setState ,除非你正在等待每个回调,因为你不能确定每个人都会在下一个之前完成.
推荐阅读
- javascript - 如何使用正则表达式验证 ISO8601 日期?
- python - (Python)获得最大递归错误,在这种情况下我应该尝试另一种方法还是覆盖它?
- php - php在表单外提交变量?
- dynamic - 考试包 - 为 Moodle 设置多项练习测验
- c - 为什么不是正在读取的文件的最后一个数值?
- javascript - 文本不显示在图像上 CSS HTML JS
- dart - 为什么 Dart 充当引用传递?
- reactjs - 如何在 Material UI 中将鼠标悬停在卡片上时放大卡片大小?
- python - Discord.py bot 中断 mp3
- html - 为什么我的网站没有使用 Bootstrap 覆盖整个屏幕?