简体   繁体   中英

I am passing the props to a functional component via Link (react-router-dom) but it says the state is 'undefined'

I need to pass the id to a different component.

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

const Option = () => {
  return (
    <section className="section">
      <Link
        to={{
          pathname: "/person",
          state: { id: "12345" },
        }}
      >
        <button class="button is-primary">Click Me</button>
      </Link>
    </section>
  );
};
export default Option;

The component where I am accessing the id

const Person = (props) => {
  let data = useLocation();
  console.log(data);
  return (
    <section className="section has-text-centered mt-4">
      <h1>Hello</h1>
    </section>
  );
};

export default Person;

But I am getting state as undefined . How do I access the id that I have passed in?

State is undefined

You need to assign the passing props on route component assigned place not ah route navigation

Reference Example for passing props to router

Or else if you really do like passing props on onclick. use useHistory hook then pass the state param

you could receive the state value via props in child component

Updated

you should pass the render params to the component like

<Route path="/person" render={Person} />

Is equal to

<Route path="/person" render={(params)=><Person {...params}/>} />

Then only you can receive the props value on child param

CodeSandBox

import { Link,useHistory } from "react-router-dom";
    
    const Option = () => {
      const history = useHistory();
      function nav(){
         history.push({
          pathname: '/path',
          state: {  // location state
            update: true, 
          },
        });
      } 
      return (
        <section className="section">
            <button class="button is-primary" onClick={nav}>Click Me</button>
        </section>
      );
    };
    export default Option;

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