如何在从一个页面导航到另一页面时在反应 hookrouter 中传递状态或道具

How to pass state or props in react hookrouter while navigate from one page to another page

我已经尝试 useRouteshookrouter 从一个页面导航到另一个页面,效果很好。我想用那条路线传递一些物体。我应该如何传递一个对象?我已经阅读了 hookrouter GitHub 页面,但我还是没明白。我试过 navigate("/home",true,{name:"batman"});,但没有用。我该怎么做?

你可以在react-router-dom中使用link组件。

import { Link } from 'react-router-dom';

<Link to={`home/${obj.name}`}> Click here </Link>

react-router 的解决方案-dom

如果您使用按钮作为路由事件触发器:

import { Button } from '@material-ui/core';
import { Link } from 'react-router-dom';

<Button
  ...
  component={Link}
  to={{
    pathname: `yourRoutePath`,
    // write your custom state below
    state: {
      otherCustomState: value,
      // sample below
      prevPath: history.location.pathname,
    }
  }}
>
  next page
</Button>

用法

history.location.state.yourCustomState

更新:

hookrouter 解决方案

传递URL参数:参考文章here,不知道是否符合你的需求

const routes = {
  '/user/:id': ({id}) => <User userId={id} />
}

传递隐式道具:参考passing-additional-data-to-route-functions

的文档
const routes = {
    '/' => () => (product) => <GeneralInfo product={product} />,
    '/details': () => (product) => <Techdetails product={product} />,
    '/buy': () => (product) => <BuyOptions product={product} />
    '/buy/:variant': ({variant}) => (product) => <Buy product={product} variant={variant} />
};

const ProductPage = ({id}) => {
    const [productObj, status] = useProduct(id);
    const match = useRoutes(routes);

    if(!match){
        return 'Page not found';
    }

    if(status.loading){
        return 'Loading product...';
    }

    return match(productObj);
};