首页 > 解决方案 > 在反应中使用客户端搜索

问题描述

搜索功能在控制台日志中运行良好,但是当我尝试将该值分配给作为状态的行时。所以我在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>
             )
        }

标签: reactjssearchsetstate

解决方案


好的,让我们从在构造函数中绑定你的函数开始,而不是在标记中,清理东西: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 ,除非你正在等待每个回调,因为你不能确定每个人都会在下一个之前完成.


推荐阅读