首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将withRouter封装在ES7函数中

将withRouter封装在ES7函数中
EN

Stack Overflow用户
提问于 2021-11-03 03:22:01
回答 2查看 137关注 0票数 0

我有一个DetailProducts函数,如何在withRouter中包装DetailProducts。谢谢

代码语言:javascript
复制
import React from "react";
import details from "../../CSS/ProductsCss/details.css";
import { withRouter } from "react-router-dom";

export default function DetailProducts() {
  return (
    <div className="single-product">
      
    </div>
  );
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-11-03 03:58:29

将反应性路由器-dom的Provider放在该组件的祖先上

代码语言:javascript
复制
import { StrictMode } from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router } from "react-router-dom";
import App from "./App";

// for example I put it in the really beginning of the app
// you may change the placement of <Router />
ReactDOM.render(
  <StrictMode>
    <Router>
      <App />
    </Router>
  </StrictMode>,
document.getElementById("root")
);

然后将组件封装在withRouter自组织中。

代码语言:javascript
复制
import React from "react";
import details from "../../CSS/ProductsCss/details.css";
import { withRouter } from "react-router-dom";

function DetailProducts(props) {
  // you have access to following and even more things
  const { match, location, history } = props;

  return (
    <div className="single-product">
      
    </div>
  );
}

export default withRouter(DetailProducts)

移徙:

正如版本5所建议的那样,您应该更新组件以使用钩子版本。

用钩子替换withRouter的所有用途。升级到v5.1 用钩子替换任何withRouter用法。它们能让你接触到所有相同的东西。同样,尽管withRouter在5.1中不受欢迎,但它是一个奇怪的API,当您可以用钩子组合状态时。它也很可能在将来的发行版中被废弃。帖子

这里有一个可用钩子的列表,它们的名称非常清楚,但是如果您想深入了解它们的话。检查文档中的钩子api部分

  • useHistory
  • useLocation
  • useParams
  • useRouteMatch
票数 0
EN

Stack Overflow用户

发布于 2021-11-03 04:14:08

钩子现在是首选的方法。它看起来可能是这样的:

代码语言:javascript
复制
import { useHistory } from "react-router-dom";

export default function DetailProducts() {
  const history = useHistory();

  function handleClick() {
    history.push("/some-path");
  }

  return (
    <div className="single-product">
      <button onClick={handleClick}>Click this</button>
    </div>
  );
}

检查文档是否有其他有用的钩子,这些钩子提供了来自withRouter的其他功能的覆盖率。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69819310

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档