如何使用Reaction路由器将数据从一页传送到另一页 [英] How to pass data from a page to another page using react router

查看:13
本文介绍了如何使用Reaction路由器将数据从一页传送到另一页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我了解REACT-ROUTER-DOOM,我是新手,似乎可以找到任何解决方案。我从API调用中获得了三个结果,在该API调用中,我将数据映射到UI上,现在我需要的是,如果我单击其中一个列表上的一行,我希望它将我带到一个屏幕,仅显示我所单击的那一项的详细信息。

import React, { Component } from "react";

export default class User extends Component {
  state = { userDetails: "" };

  componentDidMount() {
    axios.get(`https://urlforapi.com`)
    .then(({ data }) => {
      this.setState({
        userDetails: data
      });
    });
  }

  render() {
    const { userDetails } = this.state;
    return (
      <div>
        {userDetails
          ? userDetails.map(info => {
              return (
                <Link to="/home/userDetails">
                  <div key={info.id}>
                    <p>{info.name}</p>
                  </div>
                  <div>
                    <p>{info.age}</p>
                  </div>
                  <div>
                    <p>{info.description}</p>
                  </div>
                </Link>
              );
            })
          : null}
      </div>
    );
  }
}


推荐答案

选项1:传递路由状态

发送路由转换中的状态。

  • 使用react-router-domv5

您可以传递映射条目独有的某种状态,如info.id以及在单击链接时发生的路由推送。这会混淆来自用户的数据,因为您不会将信息泄露给用户界面(即浏览器)。

<Link
  to={{
    pathname: '/home/userDetails',
    state: {
      infoId: info.id,
    },
  }}
>
  • 使用react-router-domv6

V6中的链接API稍有更改,state现在是一个道具。

<Link
  to='/home/userDetails'
  state={
    infoId: info.id,
  }
>
然后,您可以从该路线返回的组件上的location道具/对象解包状态。如果用户已从其他位置导航到'/home/userDetails',则使用保护,因为state可能是未定义的。

如果通过路线道具:

props.location && props.location.state && props.location.state.infoId

props.location?.state?.infoId

如果使用函数组件,则还可以使用useLocation反应挂钩:

const { state: { infoId } = {} } = useLocation();

选项2:在URL中传递内容

<Link to={`/home/userDetails/${info.id}`>

并从返回的路由组件中的match道具中检索参数。例如,如果路由如下所示:

<Route path="/home/userDetails/:infoId" component={... } />

然后在组件中获取id:

props.match.params.infoId

对于功能组件,useParams反应挂钩:

const { infoId } = useParams();

用户可以看到这一点,但您不必使用保护模式来访问,因为根据定义,它将由路由定义(尽管infoID如果用户输入无效的ID,仍可以定义)。

这篇关于如何使用Reaction路由器将数据从一页传送到另一页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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