react类组件中的URL参数 [英] URL parameter in react Class Component

查看:37
本文介绍了react类组件中的URL参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to pass parameter to component using URL.I'm using react component not functionnel component so I can't use hooks? How can I read url parameter in class component ? I'm trying to pass parameter to a component so it can depending on parameter fetch data from database and update it or just create a new record! Thanks

推荐答案

您可以使用 withRouter HOC 装饰器.这会装饰一个组件(基于类的或函数式的)并注入 matchlocationhistory 道具.

You can use the withRouter HOC decorator. This decorates a component (either class-based or functional) and injects match, location, and history props.

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);

match 道具就是其中之一允许您访问 URL 参数

The match prop is the one that allows you to access the URL params

this.props.match.params

这篇关于react类组件中的URL参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆