从react-router获取url参数并在Component中使用

时间:2020-10-27 16:58:40

标签: javascript reactjs react-router

我想从此反应路由器(App.js)的网址中获取 id 参数

import React from "react";
import ReactDOM from "react-dom";
import Main from "./ui.js";
import Master from "./master.js";
import FireCess from "./FireCess";
import { Component } from "react";
import { BrowserRouter, Route,Link, Switch } from "react-router-dom";

class App extends Component{
    render(){
        return(
        <div className="root">
        <BrowserRouter>
          <Switch>
          <Route exact path="/masters/:id/PropertyTax/FireCess" component={FireCess}/>
          <Route exact path="/masters/pb/tenant/tenants" component={Master} />
          <Route exact path='/' component={Main} />
           
          </Switch>
        </BrowserRouter>
      </div>
        );
    }
}

export default App

我想在FireCess组件(FireCess.js)内其他URL中使用该 id 参数

import React from "react";
import Admin from "react-crud-admin";
import Form from "react-jsonschema-form";
import axios from "axios";
import Select from 'react-select';
import Master from "./master.js";

import { BrowserRouter, Route,Link, Switch, useParams } from "react-router-dom";

import "react-crud-admin/css"; //optional css import


export default class FireCess extends Admin {
  constructor(props) {
    super();
   
    
    this.name = "Tenant";
    this.name_plural = "Tenants";
    this.list_display_links = ["rate"];
    this.list_display = ["rate","fromFY"];
   
    this.list_per_page = 10;
  

  
  }
  

  get_queryset(page_number, list_per_page, queryset) {

    axios.get("/masters/:id/PropertyTax/FireCess",{
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      }
    
    }).then(response => {

   
      this.set_queryset(response.data);

    });

    return queryset;


  }
  }

如何在组件内部获取id参数?

我尝试使用this.props.match.params.id,但收到一条错误消息,提示TypeError:无法读取未定义的属性“ match”。(路由器的版本为^ 5.2.0)

1 个答案:

答案 0 :(得分:2)

您尚未在URL中定义:id,这就是为什么在错误中未定义它的原因,所以代替此

axios.get("/masters/:id/PropertyTax/FireCess",{
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  }

声明一个代表id的变量;像这样:

const id = yourId;

axios.get(`/masters/${id}/PropertyTax/FireCess`, {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      }