首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过属性性能缓存搜索大型对象

通过属性性能缓存搜索大型对象
EN

Stack Overflow用户
提问于 2017-05-18 20:50:01
回答 1查看 31关注 0票数 0

我有一个巨大的js对象,可以保存所有用户的帖子,

有些用户在这个对象中可能有更多的300+帖子,所以我想实现一种搜索机制。

示例:

代码语言:javascript
复制
{
 postById:{
   1:{ id:1, title:'varchar 250 string' },
   2:{ id:2, title:'varchar 250 string' },
   ...etc for 300+ items
 }
}

ps.:我使用ES6,这是一个反应-本地项目。

一种简单的搜索方法可以是:

代码语言:javascript
复制
_handlSearch(keyword){
  const key= keyword.toLowerCase();
  return Object.keys(postById).filter(id=>posts[id].title.indexOf(key)>-1)
               .map(id=>postById[id])
}

现在这个函数很好,问题是我应该多久触发一次搜索呢?让我们假设用户输入"var“就会触发搜索,然后添加一个新的字母"varc”,这样就可以不过滤主对象购买,而是搜索来自"var“的已经很短的列表。

是否已有优化这种自动完成/搜索功能的解决方案?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-18 21:10:50

已更新。

您可以将主列表设置为list状态属性,然后在其中反复搜索,直到没有在组件中包含当前关键字的关键字为止。

基本上,这个版本:

代码语言:javascript
复制
import React, { Component } from 'react';

class ShortList extends Component {

  constructor(props){
      super(props);
      this.state = {list:props.master,keyword:String(props.keyword||'').toLowerCase()};
      this._hadleSearchMaster = this._hadleSearchMaster.bind(this)
      this.trigger = this.trigger.bind(this)
      this.extract = typeof props.getValue==='function' ? props.getValue : f=>String(f);
      this.minLength = props.minLength||3;
      this.debounce = 0;
  }
  _hadleSearchMaster(){
    const list = Object.keys(this.props.master).map(id=>this.extract(this.props.master[id]).indexOf(this.state.keyword)>-1);
    console.log('searched master and returned'+this.state.keyword,Object.keys(this.props.master),list);
    this.setState({list});
  }
  trigger(){
    clearTimeout(this.debounce);
    this.debounce = setTimeout(this._hadleSearchMaster, 200);
  }
  componentWillReceiveProps(props){
    this.extract = typeof props.getValue==='function' ? props.getValue : f=>String(f);
    if(props.getValue!==this.props.getValue)this.extract = props.getValue;
    if(props.minLength!==this.props.minLength)this.minLength = props.getValue;

    if(!props.keyword || props.keyword.length < this.minLength)return;
    if(props.keyword===this.props.keyword)return;
    
    const keyword = String(props.keyword||'').toLowerCase();
    const stateToSet = {keyword};
    if (keyword.substr(0, this.state.keyword.length) !== this.state.keyword) {
      stateToSet.list = props.master;      
    }
    this.setState(stateToSet,
                  this.trigger)

  }
  render() {
    return this.props.render(this.state.list);
  }
}
//<Shortlist master={{}} style={{}} getValue={f=>f.title.toLowerCase()} keyword='search' render={idList=>null} minLength={3} />
export default ShortList

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44057532

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档