【问题标题】:How to parse a query string in React Router如何在 React Router 中解析查询字符串
【发布时间】:2019-12-11 10:06:21
【问题描述】:

您好,我正在使用 react 路由器,我需要传递一些查询字符串参数

试过

<Route path="/result/:type?/?filter=:filter?" exact strict component={Result}/>

我期待它能够捕获类似的网址

/result
/result/animals
/result/cars
/result/animals?filter=cats,dogs
/result/cars?filter=sedan,truck

正确的方法是什么?

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    对于url参数,如/animals/cars,可以使用冒号语法/:type

    但是对于查询参数,比如?filter=something,需要解析查询字符串。

    根据 react-router 文档:

    React Router 对如何解析 URL 没有任何意见 询问 字符串。一些应用程序使用简单的 key=value 查询字符串,但是 其他人在查询字符串中嵌入数组和对象。所以这取决于你 自己解析搜索字符串。

    在支持的现代浏览器中 the URL API ,您可以实例化一个 URLSearchParams 对象 location.search 并使用它。

    browsers that do not support the URL API (read: IE) 您可以使用第三方库,例如 query-string

    例如,在您的组件中,您将拥有location 作为来自父级Route 的道具(或者您可以从withRouter 获取它),然后您可以使用location.search 像这样解析查询字符串:

    function Parent({location}) {
      let params = new URLSearchParams(location.search);
    
      return <Child name={params.get("filter")} />;
    }
    

    更多信息:

    【讨论】:

      【解决方案2】:

      旧版本的 React Router 提供了此功能,但最终他们认为处理跨浏览器的变化太麻烦了。

      从当前版本(v4)开始,您需要使用库,例如​​query-string

      要考虑的另一个选项:如果您知道您的目标浏览器支持URLSearchParams API,则可以改用它。

      安装包:

      yarn add query-string

      用法:

      import queryString from 'query-string'
      
      ...
      
      componentDidMount() {
        const values = queryString.parse(this.props.location.search)
      }
      

      【讨论】:

        【解决方案3】:

        你需要使用不需要在Route中添加查询字符串的库:

        这是一个例子:

        import React from "react";
        import qs from "query-string";
        
        const Home = (props) => {
          console.log(props.location.search);
          const query = qs.parse(props.location.search, {
            ignoreQueryPrefix: true
          });
          console.log(query);
          return (
            <div>
              <h1>Welcome to the Tornadoes Website!</h1>
            </div>
          );
        };
        
        export default Home;
        

        Edit @ CodeSandbox

        【讨论】:

        • 这不起作用。说无法读取未定义的属性“搜索”
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-16
        • 1970-01-01
        • 2019-06-21
        • 1970-01-01
        • 2017-06-20
        • 1970-01-01
        相关资源
        最近更新 更多