如何在 React Router v6 中使用 withRouter 来传递 props?

JS3*_*JS3 11 javascript reactjs react-router-dom

以前,你需要包装这样的东西export default withRouter(name of component) ,现在在react-router v6中有所不同。

我有这个按钮,一旦您单击此按钮,它将带您进入另一个页面,其中包括 my tableMeta.rowData[0]. 我尝试使用navigate = useNavigate(),但我不知道如何传递 的值tableMeta.rowData[0]

   {
      name: "Edit",
      options: {
        customBodyRender: (value, tableMeta, updateValue) => {
          return (
            <Button
              color="success"
               onClick={
            () => navigate("/edit-products")
            // console.log(tableMeta.rowData[0])
          }
            >
              Edit
            </Button>
          );
        },
      },
    },
Run Code Online (Sandbox Code Playgroud)

在 React-router v6 中,我怎样才能像withRouter以前一样做到这一点?

San*_*hah 31

它已被弃用。您可以使用 hooks 版本重新创建它:

import React from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';

export function withRouter<ComponentProps>(Component: React.FunctionComponent<ComponentProps>) {
    function ComponentWithRouterProp(props: ComponentProps) {
        const location = useLocation();
        const navigate = useNavigate();
        const params = useParams();

        return <Component {...props} router={{ location, navigate, params }} />;
    }

    return ComponentWithRouterProp;
}

Run Code Online (Sandbox Code Playgroud)

欲了解更多详细信息,请查看此

  • 刚刚完成实施并且它有效。谢谢 (2认同)
  • 如果我使用这个“withRouter”来包装一个组件,是否可以访问该组件中的“history”?我在尝试在组件内执行 `history.push('/')` 时遇到问题,因为 `history` 未定义。 (2认同)
  • 您需要使用“useNavigate”而不是“useHistory”。[参考](https://reactrouter.com/docs/en/v6/upgrading/v5#use-usenavigate-instead-of-usehistory) (2认同)