react-router-dom useParams() 在类组件中 [英] react-router-dom useParams() inside class component

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

问题描述

我正在尝试加载基于 react-router-dom 路由的详细信息视图,该路由应该获取 URL 参数 (id) 并使用它来进一步填充组件.

I'm trying to load a details view based on a react-router-dom route that should grab the URL parameter (id) and use that to further populate the component.

我的路由看起来像 /task/:id 并且我的组件加载正常,直到我尝试从 URL 中获取 :id 像这样:

My route looks like /task/:id and my component loads fine, until I try to grab the :id from the URL like so:

import React from "react";
import { useParams } from "react-router-dom";

class TaskDetail extends React.Component {
    componentDidMount() {
        let { id } = useParams();
        this.fetchData(id);
    }

    fetchData = id => {
        // ...
    };

    render() {
        return <div>Yo</div>;
    }
}

export default TaskDetail;

这会触发以下错误,我不确定在哪里正确实现 useParams().

This triggers the following error and I'm unsure where to correctly implement useParams().

Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

文档仅显示基于功能组件的示例,而不是基于类的示例.

The docs only show examples based on functional components, not class based.

感谢您的帮助,我是新手.

Thanks for your help, I'm new to react.

推荐答案

您可以使用 withRouter 来完成此操作.只需将导出的分类组件包装在 withRouter 内,然后您就可以使用 this.props.match.params.id 来获取参数而不是使用 useParams().您还可以使用 withRouter 获取任何 locationmatchhistory 信息.都是在this.props

You can use withRouter to accomplish this. Simply wrap your exported classed component inside of withRouter and then you can use this.props.match.params.id to get the parameters instead of using useParams(). You can also get any location, match, or history info by using withRouter. They are all passed in under this.props

使用您的示例,它看起来像这样:

Using your example it would look like this:

import React from "react";
import { withRouter } from "react-router";

class TaskDetail extends React.Component {
    componentDidMount() {
        const id = this.props.match.params.id;
        this.fetchData(id);
    }

    fetchData = id => {
        // ...
    };

    render() {
        return <div>Yo</div>;
    }
}

export default withRouter(TaskDetail);

就这么简单!

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

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