首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在从一个页面导航到另一个页面时在react hookrouter中传递状态或属性

如何在从一个页面导航到另一个页面时在react hookrouter中传递状态或属性
EN

Stack Overflow用户
提问于 2020-02-12 14:39:46
回答 2查看 2.3K关注 0票数 0

我尝试过hookrouter中的useRoutes,从一个页面导航到另一个页面,运行正常。我想用这条路线传递一些对象。我应该如何传递一个对象?我看过hookrouter的GitHub页面,但还是没看懂。我像navigate("/home",true,{name:"batman"});一样试过了,但没用。我该怎么做呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-02-12 14:48:28

react-router-dom解决方案

如果使用button作为路由事件触发器:

代码语言:javascript
复制
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>

用法

代码语言:javascript
复制
history.location.state.yourCustomState

更新:

hookrouter解决方案

传递URL参数:请参考文章here,不确定它是否符合您的要求

代码语言:javascript
复制
const routes = {
  '/user/:id': ({id}) => <User userId={id} />
}

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

代码语言:javascript
复制
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);
};
票数 0
EN

Stack Overflow用户

发布于 2020-02-12 14:48:15

您可以使用react-router-dom中的链接组件。

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

<Link to={`home/${obj.name}`}> Click here </Link>
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60182493

复制
相关文章

相似问题

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