1

我想在反应应用程序中使用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>
  )
}
4

1 回答 1

4

查看 lunr文档,可以像这样创建 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…&quot;,
    author: "William Shakespeare",
    id: "1"
  });
});

然后useLunr钩子可以获取index并使用它进行搜索。

这是一个将所有这些组合在一起的沙盒!

希望这可以帮助!

于 2020-02-03T22:15:53.870 回答