React router - 将 api 数据传递给链接的组件以打开新页面 [英] React router - pass api data to the linked component to open with a new page

查看:58
本文介绍了React router - 将 api 数据传递给链接的组件以打开新页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解在这里设计路由.例如 -

I am struggling to understand to design the routing here. For example -

array.map((each)=>(
         <Link to="details/${each.id}"> <Card props={each}/> </Link>
    ))

通过点击这些卡片,详细页面的骨架将打开,但我如何将一些与卡片相关的数据传递到新页面?我想将一些api数据发送到与每张卡片相关的新页面,或者在切换到该新组件页面后传递一些信息以调用与该卡片相关的api.

by clicking on these cards, the skeleton of detailed page will open but how am i going to pass some data related to the card to the new page? I want to send some api data to new page related to each card or pass some information to call api related to that card after switching to that new component page.

推荐答案

使用路由转换发送数据

您可以使用 Link反对.

至:对象

可以具有以下任何属性的对象:

An object that can have any of the following properties:

  • pathname:一个字符串,表示要链接到的路径.
  • 搜索:查询参数的字符串表示.
  • hash:放入 URL 的哈希值,例如#a-hash.
  • state:坚持到该位置的状态. <-- 你需要这个

array.map((each)=>(
  <Link
    to={{
      pathname: `details/${each.id}`,
      state: {
        // whatever you need to send with the route transition
      },
    }}
  >
    <Card props={each}/>
  </Link>
))

接收路由状态

你有几个选择.

  1. 现在使用 useLocation React 钩子的最简单、更常用的方法在功能组件中.

  1. Easiest and more common way now with using the useLocation React hook in functional components.

const { state } = useLocation();

  • 使用 withRouter 高阶组件装饰组件并注入 路由道具.

  • Decorating a component with the withRouter Higher Order Component and inject route props.

    如果你的组件用 withRouter 装饰,它会将当前的路由 props 作为 props 注入.

    If your component is decorated with withRouter it will have the current route props injected as props.

     export default withRouter(EachComponent);
    

    location 属性访问 state.

     const { state } = this.props.location;
    

  • Route 组件直接渲染并接收 路线道具.

  • Directly render by a Route component and receive the route props.

    如果您的组件是由 Route 直接渲染的,那么它会将路由道具传递给它.

    If your component is rendered directly by a Route it will have the route props passed to it.

     <Route path="/details/:id" component={EachComponent} />
    

    location 属性访问 state.

     const { state } = this.props.location;
    

  • 注意: 路由状态是暂时的,这意味着它只存在于从一个路由到下一个路由的转换过程中.如果您直接导航到接收路由,它将没有状态,因为它没有使用提供状态的路由的转换.

    Note: Route state is transient, meaning it only exists during the transition from one route to the next. If you navigate directly to a receiving route it won't have the state because it didn't use the transition from the route providing the state.

    这篇关于React router - 将 api 数据传递给链接的组件以打开新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆