首先,我会说这是我在Node或React.js上工作的第四天,所以请容忍我。
我正在为Docusaurus 2构建一个定制的离线搜索函数,我已经构建了一个JSON索引,并创建了一个用弹力搜索它的函数。我想重定向到一个单独的结果页面,但我有问题的重定向,尽管试图遵循多个例子。这是我的index.js SearchBar。
import React, {Component} from 'react';
import {Redirect} from 'react-router-dom';
import classnames from 'classnames';
import elasticlunr from 'elasticlunr';
let siteIndex = require('./siteIndex.json');
class Search extends Component {
constructor(props) {
super(props);
this.state = {
results: [],
term: '',
index: elasticlunr(function () {
this.setRef('id');
this.addField('title');
this.addField('body');
this.addField('url');
})
};
this.toggleSearchPressEnter = this.toggleSearchPressEnter.bind(this);
this.changeTerm = this.changeTerm.bind(this);
}
init() {
let siteIndexKeys = Object.keys(siteIndex);
siteIndexKeys.forEach(key => {
this.state.index.addDoc(siteIndex[key]);
});
}
changeTerm(e) {
this.setState({term: e.target.value});
}
toggleSearchPressEnter(e) {
if (e.key === "Enter") {
this.init();
let siteSearch = this.state.index.search(e.target.value, {}); // Empty dictionary here fixes the warning about using the default configuration because you didn't supply one!
let docs = this.state.index.documentStore.docs;
this.state.results = siteSearch.slice(0, 5).map(searchKey => docs[searchKey.ref]);
if (this.state.results.length > 0) {
this.renderRedirect();
}
}
}
renderRedirect() {
console.log("Go home!");
console.log(this.state.results.length);
console.log(this.state.results);
// window.location = "/"
<Redirect
to={{
pathname: '/',
state: { results: this.state.results }
}}
/>
}
render() {
return (
<div className="navbar__search" key="search-box">
<span
aria-label="expand searchbar"
role="button"
className={classnames('search-icon', {
'search-icon-hidden': this.props.isSearchBarExpanded,
})}
tabIndex={0}
/>
<input
id="search_input_react"
type="search"
placeholder="Search"
aria-label="Search"
className={classnames(
'navbar__search-input',
{'search-bar-expanded': this.props.isSearchBarExpanded},
{'search-bar': !this.props.isSearchBarExpanded},
)}
onKeyPress={this.toggleSearchPressEnter}
/>
</div>
);
}
}
export default Search;因为我们有问题将结果重定向到结果页面,所以我想看看是否可以直接转到主页。我看到了“回家去!”在浏览器控制台中,当用户点击搜索栏上的enter时,不会发生重定向。我已经注释掉了javascript重定向,如果我从Redirect中注释掉它就会起作用。
我尝试过在return()的周围添加一个Redirect,但这似乎没有什么区别。
如果您想要复制问题
npx @docusaurus/init@next init docs classic
npm run swizzle @docusaurus/theme-search-algolia SearchBar用上述问题所在的代码替换src/theme/SearchBar/index.js的内容。
要生成JSON索引:
generate-index.js
const fs = require('fs-extra');
const path = require('path');
const removeMd = require('remove-markdown');
let searchId = 0;
const searchDoc = {};
async function readAllFilesAndFolders(folder) {
try {
const topFilesAndFolders = fs.readdirSync(folder);
for (let i = 0; i < topFilesAndFolders.length; i++) {
const file = topFilesAndFolders[i];
const fileOrFolderPath = `${folder}/${file}`;
const stat = fs.lstatSync(fileOrFolderPath);
if (stat.isFile() && path.extname(fileOrFolderPath) === '.md') {
console.log(`Got Markdown File ${file}`);
fs.readFile(fileOrFolderPath, (err, data) => {
if (err) throw err;
const regex = /title: .*\n/g;
let search = data.toString().match(regex);
let docTitle = search[0].toString().replace("title: ", "");
console.log("doctitle: ", docTitle);
if (!docTitle) {
docTitle = file.replace('.md', '');
generateSearchIndexes(fileOrFolderPath, file, docTitle);
}
else {
generateSearchIndexes(fileOrFolderPath, file, docTitle);
}
});
} else if (stat.isDirectory()) {
console.log(`Got Directory ${file}, Started Looking into it`);
readAllFilesAndFolders(fileOrFolderPath, file);
}
}
} catch (error) {
console.log(error);
}
}
function generateSearchIndexes(fileOrFolderPath, file, docTitle) {
try {
let fileContent = fs.readFileSync(fileOrFolderPath, 'utf-8');
let body = removeMd(fileContent).replace(/^\s*$(?:\r\n?|\n)/gm, '');
let title = docTitle.trim();
let url = fileOrFolderPath
.replace('.md', '')
.trim();
searchDoc[file.replace('.md', '').toLowerCase()] = { id: searchId, title, body, url };
fs.writeFileSync('src/theme/SearchBar/siteIndex.json', JSON.stringify(searchDoc), 'utf-8');
searchId = searchId + 1;
} catch (error) {
console.log('Failed to generate fail:', error);
}
}
readAllFilesAndFolders('docs');一旦从默认文档构建了JSON索引,就可以尝试搜索。我没有做任何其他的改变。
我可能做了一些愚蠢的事情,希望它是容易解决的,所以请仁慈一点。我真的试过了。;)
发布于 2020-01-11 19:40:40
使用Ajay的一些指导,并在周围玩一点,我有一个可行的解决方案。
import React, {Component} from 'react';
import {Redirect} from 'react-router';
import classnames from 'classnames';
import elasticlunr from 'elasticlunr';
let siteIndex = require('./siteIndex.json');
class Search extends Component {
constructor(props) {
super(props);
this.state = {
results: [],
term: '',
search: '',
index: elasticlunr(function () {
this.setRef('id');
this.addField('title');
this.addField('body');
this.addField('url');
})
};
this.toggleSearchPressEnter = this.toggleSearchPressEnter.bind(this);
this.changeTerm = this.changeTerm.bind(this);
}
init() {
let siteIndexKeys = Object.keys(siteIndex);
siteIndexKeys.forEach(key => {
this.state.index.addDoc(siteIndex[key]);
});
}
changeTerm(e) {
this.setState({term: e.target.value});
}
toggleSearchPressEnter(e) {
if (e.key === "Enter") {
this.init();
let searchTerm = e.target.value;
let siteSearch = this.state.index.search(searchTerm, {}); // Empty dictionary here fixes the warning about using the default configuration because you didn't supply one!
let docs = this.state.index.documentStore.docs;
let searchResults = siteSearch.slice(0, 5).map(searchKey => docs[searchKey.ref]);
this.setState({
results: searchResults,
search: searchTerm,
});
}
}
render() {
if (this.state.results.length >= 1) {
return <Redirect to={{
pathname: '/results',
state: {
results: this.state.results,
search: this.state.search
}
}} />
}
return (
<div className="navbar__search" key="search-box">
<span
aria-label="expand searchbar"
role="button"
className={classnames('search-icon', {
'search-icon-hidden': this.props.isSearchBarExpanded,
})}
tabIndex={0}
/>
<input
id="search_input_react"
type="search"
placeholder="Search"
aria-label="Search"
className={classnames(
'navbar__search-input',
{'search-bar-expanded': this.props.isSearchBarExpanded},
{'search-bar': !this.props.isSearchBarExpanded},
)}
onKeyPress={this.toggleSearchPressEnter}
/>
</div>
);
}
}
export default Search;https://stackoverflow.com/questions/59686256
复制相似问题