userQuery 在 <Route /> 中未定义

userQuery is undefined in <Route />

我即将完成使用 ReactiveSearch 构建我的搜索 UI,只需要弄清楚如何使用 React Router 4 和 npm 包查询字符串在“/results”上显示结果。

我在这里做了一个codesandbox

我的问题是为什么 userQuery 未定义?我以为我遵循 this 正确?

基本上我的搜索-layout.js是这样的:

import React, { Component } from 'react';
import { Route } from 'react-router-dom';
import querystring from 'query-string';

import Results from '../components/search/Results';

class SearchLayout extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: ''
    };
  }

  componentDidMount(value) {
    this.setState({ value: this.state.value });
    console.log('This is the value: ', value);
    const userQuery = querystring.parse(this.props.location.search);
    // this.setState({ userQuery: this.state.userQuery });
    console.log('This is from query-string: ', userQuery);
  }

  render() {
    const { value } = this.state;
    console.log('This is value: ', value);
    const { userQuery } = this.state; // query string
    console.log('This is the userQuery: ', userQuery);
    const { match } = this.props; // path
    console.log('This is match props: ', match);

    return (
      <div>
        <Route path={`${match.path}?q=${userQuery}`} component={Results} />
        {this.state.value}
        {match.path}
        <br />
        {match.url}
        <br />
        {/* <Results /> */}
      </div>
    );
  }
}

export default SearchLayout;

<Route /> 正在呈现的结果组件包含 ReactiveList 组件。我知道 <Results /> 工作并显示信息,因为我最初只是让 React 渲染它——只是为了确保它工作。现在我正在尝试集成 RR4 和查询字符串包,但不确定哪里出错了。

如果我将 path={${match.path}?q="${userQuery}"} 替换为 path="/results" - 结果显示,但不显示基于用户查询,它只是默认的 ReactiveList 行为。

好的,首先让我们看看您传递给 query-string 的内容以及 query-string 想要的内容,例如我们在文本框中输入 aaa,您传递 ?q="aaa" 但查询字符串想要 ?q=aaa

所以让我们删除 "" 周围的查询刺激:

 const fixedQuery = this.props.location.search.replace(/['"]+/g, "");
 console.log(fixedQuery );
 const userQuery = querystring.parse(fixedQuery );
 console.log(JSON.stringify(userQuery));
 console.log(JSON.stringify(userQuery.q));

请检查这个Sandbox