您的位置:首页 > Web前端 > React

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

2020-08-20 11:59 771 查看

使用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将搜索添加到我们的应用程序中。

什么是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! 😱

现在,如果您重新加载页面,则该页面为空! 😱

That's because by default, Fuse sees our empty query and doesn't match it to anything. If we now search for something like

slurms
, we can see our search dynamically update with results!

这是因为默认情况下,Fuse会看到我们的空查询,并且不匹配任何查询。 如果现在搜索

slurms
类的
slurms
,我们可以看到搜索结果动态更新!

If we wanted to fix this though so that all of our results show when there's no query, we can do so with an

if
statement or in my example, a ternary, that will show all of the characters if there is no query:

如果我们想解决此问题,以便在没有查询的情况下显示所有结果,则可以使用

if
语句或在我的示例中为三进制,如果没有查询,它将显示所有字符:

const characterResults = query ? results.map(character => character.item) : characters;

And with that, we have our basic search!

至此,我们有了基本的搜索!

Follow along with the commit!

跟随提交!

接下来我该怎么办? (What can I do next?)

调整搜索 (Tuning your search)

Fuse.js comes with a lot of options that you can use to tune your search to however you'd like. Want to only show confident results? Use the

threshold
option! Want case sensitive queries? Use the
isCaseSensitive
option!

Fuse.js带有许多选项,您可以根据需要将其调整为搜索。 是否只想显示自信的结果? 使用

threshold
选项! 需要区分大小写的查询吗? 使用
isCaseSensitive
选项!

https://fusejs.io/api/options.html

https://fusejs.io/api/options.html

使用URL参数设置默认查询 (Setting the default query with URL parameters)

Sometimes you want someone to be able to link to a particular set of results. To do this, we might want to be able to add a new URL parameter like

?q=bender
.

有时您希望某人能够链接到一组特定的结果。 为此,我们可能希望能够添加一个新的URL参数,例如

?q=bender

To make this work, you can grab that URL parameter with javascript and use that value to set our

query
state.

要使此工作正常进行,您可以使用javascript捕获该URL参数,然后使用该值设置我们的

query
状态。

加入对话! (Join the conversation!)

翻译自: https://www.freecodecamp.org/news/how-to-add-search-to-a-react-app-with-fuse-js/

使用fuse.js

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: