简体   繁体   中英

React Routes and Components prop mix

I have the following line of code:

<Route path="/users/:id" exact ><User url={structure.users} /></Route>

In User component I do the following:

function User(props, {match}) {


    useEffect(() => {
        console.log(match);
        console.log(props);
    }, [props]);
    // ...
}

I removed a bit of the code because I only want to show what is necessary but here I see that match is undefined but it should have match.params.id from the link. How can I achieve this so i can make the full url with the url with the attached id?

React components receive only a single props object argument.

Use the Route 's render prop so you can pass the route props on to the component.

<Route
  path="/users/:id"
  exact
  render={routeProps => <User url={structure.users} {...routeProps} />}
/>

Alternatively you can use the useParams React hook to access match.params of the current Route .

import { ...., useParams, .... } from 'react-router-dom';

function User(props) {
  const { id } = useParams();

  useEffect(() => {
    console.log(id);
    console.log(props);
  }, [props]);
  // ...
}

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