【问题标题】:Pass object one page to another page using Link in React Js使用 React Js 中的链接将对象一页传递到另一页
【发布时间】:2020-12-09 02:01:03
【问题描述】:

我需要将对象一页传递到另一页。根据要求,我需要使用“链接”标签来完成。这是我的代码。

第一页如下

<Link  
        to={{
          pathname: "/2ndPage",
          state: { foo: 'bar'} 
        }}
      > Action</Link>

当我单击此按钮时,我需要将对象传递到我的第二页。这是我尝试的第二页代码

function 2ndPage(props) {
console.log(props)
  return <h1>Hello</h1>;
}

正确项目构建成功。当我单击第一个页面按钮时,页面重定向正确。但是对象没有通过。我认为这是错误的做法。你能帮我做这件事吗?

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

首先,函数名以数字开头,有点不合常规。

foo 值应位于location.state

试试这个

import { useParams} from "react-router-dom";

function TwoNdPage(props){
  let { foo } = useParams(); 
//const {foo} = props.location.state // or you can try this
  console.log(foo) // it should return bar
  return <h2>About</h2>
}
export default TwoNdPage;

【讨论】:

  • 现在错误说,TypeError: Cannot destruct property 'foo' of 'props.location.state' 因为它是未定义的。
  • @Kumara 看起来道具未定义,结构有问题。可以分享更多代码吗?
  • @Kumara 我刚刚做了一个快速的 CodeSandBox 展示了如何构建它
  • 可以用router.query代替props.location吗?
  • @VicenteC 我认为这是一种旧方法,可能在 react-router 的第 2 版中
【解决方案2】:

您的状态将位于位置对象location.state。您可以在 SecondPage 组件内使用钩子定位 useLocation。注意 location.state 如果你直接打开链接可以是未定义的,但它必须在点击链接后出现。

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

const SecondPage = () => {
  const location = useLocation();

  return (
    <p>{location.state}</p>
  );
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 2023-01-24
    • 2021-08-02
    • 1970-01-01
    相关资源
    最近更新 更多