类组件内的 react-router-dom useParams()

新手上路,请多包涵

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

我的路线看起来像 /task/:id 并且我的组件加载正常,直到我尝试从 URL 中获取 :id ,如下所示:

 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()。

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

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

原文由 Jorre 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
1 个回答

版本 <= 5:

您可以使用 withRouter 来完成此操作。只需将导出的分类组件包装在 withRouter 中,然后就可以使用 this.props.match.params.id 获取参数,而不是使用 useParams() 。您还可以获得任何 locationmatch , - - history withRouter 它们都是在 this.props 下传入的

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

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

就那么简单!

原文由 Michael Mayo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进