使用fuse.js_如何使用Fuse.js将搜索添加到React应用
使用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.gitGit 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.jsThis 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!)
🐦 Follow Me On Twitter
Twitter在Twitter上關注我
📽? Subscribe To My Youtube
Subscribe?訂閱我的YouTube
?? Sign Up For My Newsletter
??注冊我的時事通訊
翻譯自: https://www.freecodecamp.org/news/how-to-add-search-to-a-react-app-with-fuse-js/
使用fuse.js
總結
以上是生活随笔為你收集整理的使用fuse.js_如何使用Fuse.js将搜索添加到React应用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 连着两天梦到男友出轨怎么回事
- 下一篇: 梦到学校死人了有什么兆头