使用fuse.js

Search is a powerful way help people visiting your site find the content that's most important to them. But often it's really challenging to figure out the rules and logic to make that happen. In this article, we'll see how can we can use fuse.js to add search to our apps.

搜索是一种强大的方式,可以帮助访问您网站的用户找到对他们来说最重要的内容。 但是,要弄清楚实现这一目标的规则和逻辑常常是真正的挑战。 在本文中,我们将看到如何使用fuse.js将搜索添加到我们的应用程序中。

  • What is fuse.js?

    什么是fuse.js?

  • Why is search important?

    为什么搜索很重要?

  • What are we going to build?

    我们要建造什么?

  • Step 0: Bootstrapping our app

    步骤0:引导我们的应用

  • Step 1: Installing Fuse.js

    步骤1:安装Fuse.js

  • Step 2: Creating a new Fuse search instance

    步骤2:创建一个新的Fuse搜索实例

  • Step 3: Setting up dynamic search based on user input

    步骤3:根据用户输入设置动态搜索

什么是fuse.js? (What is fuse.js?)

Fuse.js is a JavaScript library that provides fuzzy search capabilities for applications and websites. It's nice and easy to use out of the box, but also includes configuration options that allow you to tweak and create powerful solutions.

Fuse.js是一个JavaScript库,为应用程序和网站提供模糊搜索功能。 开箱即用非常好用,而且还包括配置选项,使您可以调整和创建强大的解决方案。

为什么搜索很重要? (Why is search important?)

Whether you're a content creator or are trying to sell a product with your website, it's important to help your visitors actually find what they're looking for.

无论您是内容创建者,还是试图通过您的网站销售产品,重要的是要帮助访问者实际找到他们想要的东西。

If you're building an ecommerce website, you want someone to be able to easily find your Bender vinyl figures rather than having to dig through the entire catalog first.

如果您要建立一个电子商务网站,则希望某人能够轻松找到您的Bender乙烯基人物,而不必先深入研究整个目录。

我们要建造什么? (What are we going to build?)

We're going to start off with a basic Create React App example. It's going to include some character info as structured data for one of my favorite shows Futurama that's simply dumped out into an HTML list.

我们将从一个基本的Create React App示例开始。 它将包含一些字符信息作为结构化数据,这是我最喜欢的电影《 Futurama》之一,它只是转储到HTML列表中。

With that list, we're going to use fuse.js to provide client-side search capabilities, allowing us to demonstrate searching for the character we're looking for by their name and other details.

在该列表中,我们将使用fuse.js提供客户端搜索功能,从而使我们能够演示通过其名称和其他详细信息搜索所需字符。

第0步:引导我们的应用 (Step 0: Bootstrapping our app)

To get started, we're going to need content to work with. I got started by building a list of characters from Futurama as structured json data that I put in a list with a fresh Create React App.

首先,我们需要内容才能使用。 我从构建Futurama中的字符列表作为结构化json数据开始,并使用新的Create React App将其放入列表中。

You'll also notice I've already added an input for our search. It's not yet functional but we'll use that to get started.

您还会注意到,我已经为搜索添加了输入。 它尚无功能,但我们将使用它来开始。

If you'd like to start off at the same place, I created a branch with my demo repo that you can clone locally to walk through the project with me!

如果您想在同一地方开始,我用我的演示仓库创建了一个分支,您可以在本地克隆该分支以与我一起完成该项目!

git clone --single-branch --branch start git@github.com:colbyfayock/my-futurama-characters.git

Git branch "start"

Git分支“开始”

Or follow along with the commit.

或者跟着提交 。

步骤1:安装Fuse.js (Step 1: Installing Fuse.js)

First thing we'll want to do is actually add Fuse.js to our app. In your project, run:

我们要做的第一件事实际上是将Fuse.js添加到我们的应用程序中。 在您的项目中,运行:

yarn add fuse.js
# or
npm install --save fuse.js

This will save the dependency to our project so that we'll be able to use it in our project.

这将把依赖项保存到我们的项目中,以便我们可以在项目中使用它。

Next we'll want to import the dependency to our app so that we can start building with it. At the top of your file, in our case src/App.js if you're following along with me in a new Create React App project, add:

接下来,我们要将依赖项导入到我们的应用程序中,以便我们开始使用它进行构建。 在文件顶部,如果您要跟着我一起在新的Create React App项目中,在我们的情况下为src/App.js ,请添加:

import Fuse from 'fuse.js';

If you want to test that it's working, you can console.log(Fuse) and see our Fuse class we'll use to create our search capabilities.

如果您想测试它是否正常工作,则可以console.log(Fuse)并查看我们将用于创建搜索功能的Fuse类。

And with that, we're ready to get started!

这样,我们就可以开始了!

Follow along with the commit

跟着提交

步骤2:创建一个新的Fuse搜索实例 (Step 2: Creating a new Fuse search instance)

To use Fuse.js, we'll want to first create a new instance of it.

要使用Fuse.js,我们首先要创建一个新实例。

At the top of your component, add:

在组件的顶部,添加:

const fuse = new Fuse(characters, {keys: ['name','company','species']
});

With this does:

这样做:

  • Creates a new instance of Fuse创建一个新的Fuse实例
  • Passes in our characters array of objects

    传入对象的characters数组

  • Specifies the 3 keys in our data that we want to search on指定我们要搜索的数据中的3个键

Next, to perform the search, we can add:

接下来,要执行搜索,我们可以添加:

const results = fuse.search('bender');

And if we console log out the results, we can see:

如果我们用控制台注销结果,我们可以看到:

You'll notice that we have more results than our friend Bender though. Fuse.js provides a "fuzzy search" meaning it tries to help you in case you're not sure what you're looking for or if you're misspelling your query.

您会注意到,我们的结果比朋友Bender多得多。 Fuse.js提供了一个“模糊搜索”,这意味着它可以在您不确定要查找的内容或拼写错误的查询时为您提供帮助。

To get an idea of how this works, let's add the includeScore option to our search:

为了了解其工作原理,让我们在搜索中添加includeScore选项:

const fuse = new Fuse(characters, {keys: ['name','company','species'],includeScore: true
});

Now we can see the score attribute in our results object.

现在,我们可以在结果对象中看到score属性。

You'll notice that our first result has a really low score. With fuse.js, a lower score means it's closer to an exact match.

您会注意到我们的第一个结果得分非常低。 使用fuse.js,较低的分数意味着它更接近完全匹配。

A score of 0 indicates a perfect match, while a score of 1 indicates a complete mismatch.

分数为0表示完全匹配,而分数为1表示完全不匹配。

It's saying that is incredibly likely that the first result is what we're looking for, but it's not confident in the others.

这就是说,第一个结果很有可能是我们正在寻找的结果,但对其他结果并不确定。

So with our results, we want to actually connect that to our UI. If you notice our array output is different than what we are mapping through for the HTML list, so let's create a new variable that we can change it to:

因此,根据我们的结果,我们希望将其实际连接到我们的UI。 如果您发现我们的数组输出与HTML列表所映射的输出不同,那么让我们创建一个新变量,将其更改为:

const results = fuse.search('bender');
const characterResults = results.map(character => character.item);

What this is doing is creating a new array using the map method that will only include the item property from each array object.

这样做是使用map方法创建一个新数组,该方法仅包含每个数组对象中的item属性。

Then if we replace our characters map inside of our list with characterResults.map:

然后,如果我们将列表中的characters映射表替换为characterResults.map

<ul className="characters">{characterResults.map(character => {const { name, company, species, thumb } = character;

We can now see that our page only shows the results for "bender"!

现在我们可以看到我们的页面仅显示“弯曲”的结果!

Follow along with the commit!

跟随提交!

步骤3:根据用户输入设置动态搜索 (Step 3: Setting up dynamic search based on user input)

Now that we have a hard-coded search working, we want someone to actually be able to use the search input to search!

既然我们已经进行了硬编码的搜索,那么我们希望某人实际上能够使用搜索输入进行搜索!

To achieve this, we're going to use the useState hook and listen for changes to the input field, which will dynamically create a search for our data.

为了实现这一点,我们将使用useState挂钩并侦听对input字段的更改,这将动态创建对我们数据的搜索。

First, import the useState hook from React:

首先,从React导入useState钩子:

import React, { useState } from 'react';

Next, let's use that hook to create a state instance:

接下来,让我们使用该钩子创建一个状态实例:

const [query, updateQuery] = useState('');

Here, we're creating a new state of query that we can update with updateQuery that defaults to an empty string ('').

在这里,我们正在创建一个新的query状态,可以使用updateQuery更新默认状态为空字符串( '' )。

With that, let's tell our search input to use that query value as it's value:

这样,让我们​​告诉搜索输入使用该query值作为其值:

<input type="text" value={query} />

At this point, nothing should be different, as we are using a blank query.

此时,没有什么不同,因为我们使用的是空查询。

Now let's add an event handler to our input that we can use to update our state:

现在,让我们在输入中添加一个事件处理程序,以更新状态:

<input type="text" value={query} onChange={onSearch} />

And we'll want to create that function so we can use it:

我们将要创建该函数,以便可以使用它:

function onSearch({ currentTarget }) {updateQuery(currentTarget.value);
}

This will update our query with the input's value any time it changes.

每当输入更改时,这将使用输入的值更新query

Now that our query  will have what we want to search for, we can update our search instance:

现在我们的query将具有我们要搜索的内容,我们可以更新搜索实例:

const results = fuse.search(query);

And now if you reload the page, it's blank!

使用fuse.js_如何使用Fuse.js将搜索添加到React应用相关推荐

  1. linux fuse安装脚本,Linux FUSE(用户态文件系统)的使用:用libfuse创建FUSE文件系统...

    说明 FUSE 是Linux Kernel的特性之一:一个用户态文件系统框架,a userspace filesystem framework. 形象的说就是可以在用户态运行一个程序,这个程序暴露出一 ...

  2. chosen.jquery.js 有搜索功能、多选功能的下拉框插件

    chosen.jquery.js 有搜索功能.多选功能的下拉框插件 官方源码:  https://github.com/harvesthq/chosen 该源码中的样例index.html有该插件的详 ...

  3. 原生js清空上一个元素内容_原生JS实现动态添加新元素、删除元素方法

    1. 添加新元素 动态添加新元素 Coffee Tea Coffee Tea var child = document.getElementsByClassName("child" ...

  4. 如何在React JS组件和React JS App中添加CSS样式?

    In this tutorial, we will only work with CSS styles. Please ensure you have basic knowledge of HTML, ...

  5. html+input改变图标,JS Input里添加小图标的两种方法

    我们在做网页的时候,经常需要在input里面添加小图标,那么这里就介绍比较常见的两种方法. 将小图标当做input的背景来插入,直接上代码吧: Box{ height: 50px; backgroun ...

  6. 纯js实现搜索框自动补全

    纯js实现搜索框自动补全 开发语言:HTML+CSS+JS 编辑器:VSCode 构建思路:建立两个div,一个用于输入和搜索,一个用于展示,用于展示的初始状态为隐藏的.后面当有键盘输入事件时就显示, ...

  7. js 对象中添加新属性

    js 对象中添加新属性 对象数组添加新属性 同名属性会被覆盖,相同属性会去重

  8. js给对象添加变量属性 js 更改对象中的属性名 数组对象中每个对象添加一个字段-map用法和forEarch用法

    js给对象添加变量属性 & js 更改对象中的属性名 & 数组对象中每个对象添加一个字段-map用法和forEarch用法 1.js给对象添加变量属性 1.js创建一个对象或者在原有对 ...

  9. html 点击增加样式,js点击添加css样式 css添加jq点击事件 JavaScript点击增加css样式...

    js可实现点击后对div或者其他标签增加或者删除css样式,从而达到实现点击触发某种效果的目的.页面样式可以通过style修饰,也可以通过css修饰,改变css或者添加css可以改变页面的排版.代码如 ...

最新文章

  1. VMware安装CentOS6.8详细教程
  2. WinForm容器内控件批量效验是否允许为空?设置是否只读?设置是否可用等方法分享...
  3. 三、const常量声明方式
  4. 2.1 . df 命令和du命令
  5. simplexmlelement类设置编码_超3.6万条!全国通用的医用耗材编码标准来了
  6. fcntl函数-文件控制函数
  7. Maven之依赖管理
  8. 安徽大学计算机教学平台c语言作业,安徽大学计算机基础C语言选择题
  9. 域嵌套太深_pyspark如何修改嵌套结构域
  10. neon浮点运算_ARM 浮点运算详解
  11. Linux本地无法登录,远程却可以登录
  12. Linux启动报:UNEXPECTED INCONSISTENCY: RUN fsck MANUALLY问题解决
  13. JAVA Swing GUI设计 WindowBuilder Pro Container使用大全8——JInternalFrame使用
  14. nginx基本配置与参数说明-【转】
  15. 爬取cloudmusic歌单
  16. 我在HW中用到的三款工具
  17. python交通流预测代码,使用python进行交通流量预测
  18. 五类/超五类网线与六类/超六类网线的区别及应用
  19. Deepfacelab 小白教程
  20. 费氏数列(c/python)

热门文章

  1. 第九篇 并发(进程和线程)
  2. C++ 网络开发工具
  3. SVN Cannot merge into a working copy that has local modifications
  4. 详谈P(查准率),R(查全率),F1值
  5. 【数据库】Oracle用户、授权、角色管理
  6. (hdu 简单题 128道)平方和与立方和(求一个区间的立方和和平方和)
  7. php文件操作基本使用方法
  8. 分享一个帮助你在线测试响应式设计的web工具 - Screenqueri.es
  9. Centos7下使用ELK(Elasticsearch + Logstash + Kibana)搭建日志集中分析平台
  10. instrumentation模拟很多activity的操作