【问题标题】:React search the text in an array of objects on Onchange of input在输入的 Onchange 上反应搜索对象数组中的文本
【发布时间】:2019-01-28 09:23:16
【问题描述】:

我正在尝试根据表中的搜索来操作表数据。所以,我拥有的是这种类型的数据:

this.props.datalist = {
    "content": [{
        "id": "5b7d4a566c5fd00507501051",
        "companyId": null,
        "title": "Senior/ Lead UI Developer",
        "jobDescription": null,
        "technology": "java"
    },{
        "id": "5b7d4a566c5fd005075011",
        "companyId": null,
        "title": "ead UI Developer",
        "jobDescription": null,
        "technology": "angular"
    }]
}

在这里,我的数据来自我的 `redux 状态。所以我通过将其作为道具传递给用户,以表格形式向用户展示。

我有一个搜索字段:

<input type="text"
       id="searchJob"
       className="form-control-sm border-0 flex-grow-1"
       value={this.state.search}
       placeholder="Company Name / Technology / Job title"
       onChange={this.onInputChnage} 
/>
    <i className="fa fa-search search-job"></i>

 onInputChnage = (e) => {
    this.setState({
      search: e.target.value
    }) 
  }


<div className="col-12 pr-0 pl-0">
            <UserJobsTabel jobList={filteredList} />
          </div>
        </div>

这里,我使用过滤器得到了这个数组中的过滤数据

 [{
        "id": "5b7d4a566c5fd00507501051",
        "companyId": null,
        "title": "Senior/ Lead UI Developer",
        "jobDescription": null,
        "technology": "java"
    },{
        "id": "5b7d4a566c5fd005075011",
        "companyId": null,
        "title": "ead UI Developer",
        "jobDescription": null,
        "technology": "angular"
    }]

现在,在设置状态时,

我就是这样做的。

this.setState({ search: data })

如果我想将状态设置为像 "content": [{}] 这样的键,那么我该怎么做?

因为我使用它的方式是这样的,

{this.props.dataList && this.props.dataList.content && this.props.dataList.content.length > 0 && this.props.dataList.content.sort((a, b) => b.createdAt - a.createdAt).map((item, key) => {

我想要做的是表数据有两个键。一个是titleTechnolgoy 现在,搜索发生然后它应该签入对象并返回匹配的对象,并将显示在表格上。 现在,如果搜索再次没有任何内容,那么它应该显示存在的默认数据。有没有办法做到这一点?

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案1】:

    最简单的方法是在 render 方法中创建一个包含过滤后的 props.datalist 的变量并将其用于显示。

    类似

    render(){
       const { datalist:{content} } = this.props;
       const { search } = this.state;
       const filteredList = content.filter(job=>Object.values(job).some(value=>value.includes(search)));
    
       return (<div>
         //whatever
         {filteredList.map(job=>....)}
       </div>)
    }

    您也可以在onInputChnage 中进行过滤,并将过滤后的列表存储在本地state 中。

    【讨论】:

    • 这里有两个标准,可能在技术或标题中
    • 如果没有匹配的内容,我需要显示没有匹配的内容,如果用户清除所有内容,那么它应该显示该数组中的所有数据
    • 这个数据直接来自redux的应用状态
    • @ganeshk 现在检查所有属性。如果您只想测试特定的两个,请将Object.values(.)... 更改为job.title.includes(search) || job.technology.includes(search)
    • {filteredList.length ? filteredList.map(job=&gt;....)} : &lt;div&gt;nothing found&lt;/div&gt;}之类的东西处理渲染中找不到结果的情况
    猜你喜欢
    • 2020-01-13
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    相关资源
    最近更新 更多