通过React获得对查询参数的访问

时间:2018-06-19 19:10:30

标签: reactjs react-router

我看过几篇文章,说您应该引用this.props.location以获得对查询字符串参数的访问。但是,无论我在哪里检查此属性,位置始终为“未定义”。我显然缺少了一些东西。

这是我的设置...

package.json

{
  "name": "Lender.Services.Web",
  "homepage": "/dataexchange/lender",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "bootstrap": "^3.3.7",
    "react": "^16.0.0",
    "react-bootstrap": "^0.32.1",
    "react-dom": "^16.0.0",
    "react-grid-system": "^4.1.1",
    "react-router-bootstrap": "^0.24.4",
    "react-router-dom": "^4.2.2",
    "react-scripts": "1.0.17",
    "rimraf": "^2.6.2"
  },
  "scripts": {
    "start": "rimraf ./build && react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

index.js

import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
import './index.css';
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

const baseUrl = document.getElementsByTagName('base')[0].getAttribute('href');
const rootElement = document.getElementById('root');

ReactDOM.render(
  <BrowserRouter basename={baseUrl}>
    <App />
  </BrowserRouter>,
  rootElement);

registerServiceWorker();

App.js

import React, { Component } from 'react';
import { NewRequest } from './components/NewRequest';

export default class App extends Component {
    displayName = App.name

    render() {
        return (
            <NewRequest />
        );
    }
}

如果我在render函数中破坏了App.js,则this.props.location未定义。

如何通过设置访问查询字符串参数?

1 个答案:

答案 0 :(得分:2)

反应路由器仅将路由道具注入其路由到的组件。现在您的App组件不会通过react路由器路由到,而只是呈现为顶级组件。

<BrowserRouter basename={baseUrl}>
    <App />
 </BrowserRouter>,

如果要让react-router注入路由参数,则实际上需要有一条通往App组件的路由。像这样的东西。

<BrowserRouter basename={baseUrl}>
    <Route path={"/"} exact component={App} />
 </BrowserRouter>,

现在,当您在浏览器中进入/路线时,您将看到App,但是如果您转到其他地方,您将不会看到,这是因为现在当路径匹配时,react-router会渲染您的组件,并且在渲染时也会向其注入路线道具。