【问题标题】:How to create an index with lunr js and reactjs?如何用lunr js和reactjs创建索引?
【发布时间】:2020-04-14 22:18:22
【问题描述】:

我想在 react 应用中使用 lunr js 来搜索字符串,但我不知道如何设置 lunr 索引。在文档中它说The Lunr index. This can be an instance of a Lunr index or one that has been exported via JSON.stringify.,但我不知道这是如何完成的。

import React, { useState } from 'react'
import { useLunr } from 'react-lunr'
import { Formik, Form, Field } from 'formik'

const index = /* a lunr index */
const store = {
  1: { id: 1, title: 'Document 1' },
  2: { id: 2, title: 'Document 2' },
  3: { id: 3, title: 'Document 3' },
}

const SearchBar = () => {
  const [query, setQuery] = useState(null)
  const results = useLunr(query, index, store)

  return (
    <Formik
      initialValues={{ query: '' }}
      onSubmit={(values, { setSubmitting }) => {
        setQuery(values.query)
        setSubmitting(false)
      }}
    >
      <Form>
        <Field name="query" />
      </Form>
      <h1>Results</h1>
      <ul>
        {results.map(result => (
          <li key={result.id}>{result.title}</li>
        ))}
      </ul>
    </Formik>
  )
}

【问题讨论】:

    标签: reactjs lunrjs


    【解决方案1】:

    查看 lunr docs 可以这样创建 lunr 索引:

    import lunr from "lunr";
    
    const index = lunr(function() {
      this.field("title");
      this.field("body");
    
      this.add({
        title: "Twelfth-Night",
        body: "If music be the food of love, play on: Give me excess of it…",
        author: "William Shakespeare",
        id: "1"
      });
    });
    

    useLunr 挂钩然后可以获取 index 并将其用于搜索。

    这是一个sandbox,将所有这些放在一起!

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2020-07-30
      • 1970-01-01
      • 2021-09-09
      • 2013-08-20
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多