简体   繁体   中英

Pass data from one page to another in React using Router

I am trying to pass only one string from a page to another using react router and functional components only , so I created a button that helps me link my 2 pages, but I am unable to pass my string. This is my sample code on the initial page:

 import { Link } from "react-router-dom"; import React, { useState, Component } from "react"; function FrontPageDesktop() { const [myString, setMyString] = useState("Hello"); return ( <Link to={{ pathname: "/donate", myString, }} > <TouchableOpacity> DONATE NOW </TouchableOpacity> </Link> ); }

And this is the code of the destination page:

 function DonatePageDesktop(myProps) { const { myString } = myProps.location.state; return <Text>Hello{myString}</Text>; }

And thank you!

According to the documentation you should pass the data using the state on the Link component:

import { Link } from "react-router-dom";
import React, { useState, Component } from "react";

function FrontPageDesktop() {
  const [myString, setMyString] = useState("Hello");
  return (
    <Link
      to={{
        pathname: "/donate",
        state: myString,
      }}
    >
      <TouchableOpacity> DONATE NOW </TouchableOpacity>
    </Link>
  );
}

You can pass the state key in the object which you pass to the to property of the Link component like this

<Link
  to={{
    pathname: "/donate",
    state: { myString }
  }}
>
  <TouchableOpacity> DONATE NOW </TouchableOpacity>
</Link>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM