代码之家  ›  专栏  ›  技术社区  ›  dns_nx

反应-筛选返回错误的行

  •  0
  • dns_nx  · 技术社区  · 9 年前

    我快疯了。我创建了一个包含多个条目的列表。我添加了一个过滤函数,看起来效果不错。我检查了返回的结果数,但不知怎么的,它只是显示了从第一行开始的结果数。

    解释:

    ...    
    render() {
    let filteredList = this.state.freights.filter((freight) => {
        let search = this.state.search.toLowerCase();
        var values = Object.keys(freight).map(function(itm) { return freight[itm]; });
        var flag = false;
    
        values.forEach((val) => {
            if(val != undefined && typeof val === 'object') {
                var objval = Object.keys(val).map(function(objitm) { return val[objitm]; });
                objval.forEach((objvalue) => {
                    if(objvalue != undefined && objvalue.toString().toLowerCase().indexOf(search) > -1) {
                        flag = true;
                        return;
                    }
                });
            }
            else {
                if(val != undefined && val.toString().toLowerCase().indexOf(search) > -1) {
                    flag = true;
                    return;
                }   
            }
        });
        if(flag) 
            return freight;
    });
    ...
    <tbody>
    {
        filteredList.map((freight)=> {
          return (
            <Freight freight={freight} onClick={this.handleFreightClick.bind(this)} key={freight.id} />
          );
        })
    }
    </tbody>
    ...
    

    freights 通过AJAX JSON结果加载和填充。一个对象 货物 看起来像这样:

    enter image description here

    我有一个文本框,用户可以在其中执行搜索。此搜索应返回所有 freight 属性包含搜索字符串的对象。

    这个 filter

    “Zones”只是用户可以搜索的搜索字符串的一个示例。

    2 回复  |  直到 9 年前
        1
  •  1
  •   Denialos    9 年前

    既然你的意图已经清楚了,我建议你采用这个简单得多的解决方案。

    isObject

    const getAllValues = (obj) => {
      return Object.keys(obj).reduce(function(a, b) {
        const keyValue = obj[b];
        if (_.isObject(keyValue)){
          return a.concat(getAllValues(keyValue));
        } else {
          return a.concat(keyValue);
        }
      }, []);
    }
    

    filter 非常简单:

    let filteredList = this.state.freights.filter((freightItem) => {
       const allItemValues = getAllValues(freightItem);
       return allItemValues.includes(this.state.search);
    });
    

    应该是这样。如果有什么事情不起作用,请喊我一声。

        2
  •  0
  •   dns_nx    9 年前

    我需要添加 freight 组件 componentWillReceiveProps

    componentWillReceiveProps(nextProps) {
        if(nextProps.freight) {
            this.setState({
                freight: nextProps.freight
            });
        }
    
    }
    

    然后一切都很好。