未显示 React 查询字符串

React Query String not being displayed

我正在使用查询字符串传递一些参数并呈现以下组件

import React, { Component } from "react";
class Show extends Component {

  constructor(props,context) {
        super(props,context);
        this.state = {
          name: ''
        };
        console.log(this);

    }


  render() {
    return (
      <div>
        <h4>Hi {this.props.match.params.name} </h4>
        <p></p>
        {this.props.match.params.name ? <b>ID: {this.props.match.params.name}</b> : }
      </div>
    );
  }
}

export default Show;

路线如下:

    <Route path='/show/:name?' component={Show} />

但这总是导致未定义的名称,我只看到 Hi 而不是名称。我使用以下版本。

"react-dom": "^16.13.0",
"react-router-dom": "^5.1.2",
"query-string": "^6.11.1"

不确定我在哪里犯了错误。感谢任何帮助。

您可以从 location 属性中查询路径查询参数。

props.location.search

如果路由路径为 "/show/:name"match 属性将具有路径参数 name,即 props.match.params.name,并且任何 URL 查询参数将简单地附加到 URL 并且可以在 location prop.

上找到

用法:

class Show extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      name: ""
    };
    console.log(this);
  }

  render() {
    return (
      <div>
        <h4>Math Param {this.props.match.params.name} </h4>
        <h3>Query {this.props.location.search} </h3>
        <p />
        {this.props.match.params.name && (
          <b>ID: {this.props.match.params.name}</b>
        )}
      </div>
    );
  }
}

查询字符串与较长的 URL 一起使用,并在“?”之后添加一些内容。如果我输入 localhost:3000/show/bob?,props.location 对象的路径名将是 /show/bob,因此对于这条特定的路线,您并不需要它。

我在本地复制了你的代码,但没有得到 'undefined' 的名称,我得到了预期的输出。确保您的 App 组件路由被 <Router> 标记包围,如下所示:

<Router>
     <Route path='/show/:name?' component={Show} />
</Router>

此外,显示组件中的 if/else 条件需要在 else 运算符之后添加一些内容。使用 && 或在其后添加 null

如果您对钩子感兴趣,请查看 useParams() 钩子 here。它为您提供url个参数。