react类组件中的URL参数

IT技术 reactjs react-router
2021-04-30 07:45:55

我正在尝试使用 URL 将参数传递给组件。我使用的是 react 组件而不是 functionnel 组件,所以我不能使用钩子?如何读取类组件中的 url 参数?我正在尝试将参数传递给组件,以便它可以根据参数从数据库中获取数据并更新它,或者只是创建一个新记录!谢谢

2个回答

您可以使用withRouterHOC 装饰器。此装饰组件(无论是基于类的或功能性的)并注入matchlocationhistoryprops。

import React from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router";

// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  };

  render() {
    const { match, location, history } = this.props;

    return <div>You are now at {location.pathname}</div>;
  }
}

// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation);

matchprops是允许您访问 URL 参数props

this.props.match.params

您可以使用window.location读取 URL 参数