我有一个DetailProducts函数,如何在withRouter中包装DetailProducts。谢谢
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>
);
}发布于 2021-11-03 03:58:29
将反应性路由器-dom的Provider放在该组件的祖先上
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自组织中。
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部分
发布于 2021-11-03 04:14:08
钩子现在是首选的方法。它看起来可能是这样的:
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的其他功能的覆盖率。
https://stackoverflow.com/questions/69819310
复制相似问题