简体   繁体   English

我如何在 React.js 中解决这个路由问题?

[英]How Can I Fix This Routing Issue In React.js?

I will preface this with stating this is my fourth day working on Node or React.js, so please bear with me.我先声明这是我在 Node 或 React.js 上工作的第四天,所以请耐心等待。

I am building a custom, offline search function for Docusaurus 2. I have built a JSON index and created a function to search it with elasticlunr .我正在为 Docusaurus 2 构建一个自定义的离线搜索功能。我已经构建了一个 JSON 索引并创建了一个函数来使用elasticlunr进行搜索。 I want to redirect to a separate results page, however I am having issues with the redirect despite trying to follow multiple examples.我想重定向到单独的结果页面,但是尽管尝试遵循多个示例,但我在重定向时遇到了问题。 Here is my index.js for the SearchBar.这是我用于 SearchBar 的index.js

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;

Because we had issues redirecting to the results page with the results, I wanted to see if I could just go to the home page.因为我们在将结果重定向到结果页面时遇到了问题,所以我想看看是否可以直接转到主页。 I see the message "Go home!"我看到消息“回家!” in the browser console when the user hits enter on the search bar, but no redirect occurs.在浏览器控制台中,当用户在搜索栏上按 Enter 键时,但不会发生重定向。 I have commented out the javascript redirect that does work if I comment out Redirect from renderRedirect() .如果我从renderRedirect()注释掉Redirect ,我已经注释掉了确实有效的 javascript 重定向。

I have tried adding a return() around the Redirect , but it does not seem to make any difference.我尝试在Redirect周围添加return() ,但它似乎没有任何区别。

If you would like to reproduce the issue如果您想重现该问题

npx @docusaurus/init@next init docs classic
npm run swizzle @docusaurus/theme-search-algolia SearchBar

Replace the contents of src/theme/SearchBar/index.js with the code that is the problem above.src/theme/SearchBar/index.js的内容替换为上述问题的代码。

To generate the JSON index:生成 JSON 索引:

generate-index.js生成-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');

Once the JSON index is built from the default docs, the search can be attempted.一旦从默认文档构建了 JSON 索引,就可以尝试搜索。 I haven't made any other changes.我没有进行任何其他更改。

I've probably done something stupid and hopefully it is easily fixable, so please be merciful.我可能做了一些愚蠢的事情,希望它很容易修复,所以请多多包涵。 I really did try.我确实尝试过。 ;) ;)

Using some guidance from Ajay, and playing around a little, I have a working solution.使用 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM