简体   繁体   中英

Passing props through Router Link using Hooks

I am trying to pass props through the react router link. My app has a list of people, coming from a firebase database. The list of people show up fine. I am trying to make the individual profiles when you click on a person. My local host says that state is undefined in props.location.state in singleModel. Model can use its own props but wont pass the state to single model.Nothing passes through. Just need the name and gender of the clicked person for getting info from firebase.

In my app.js:

<Route path='/women/:id' exact>
  <SingleModel/></Route>

In my model.js component that is meant to be clicked:

import React, {useRef, useEffect} from 'react';
import classes from './model.module.scss';
import {Link} from 'react-router-dom';

const Model = (props) => {

    return (  
        <Link to={{
            pathname:`/women/${props.name}`,
            state:{
                name: props.name,
                gender: props.gender
            }
            }}>
        <div className={classes.model} onClick>
            <img src={props.mainImage} alt="Model Headshot"/>
            <h3>{props.name}</h3>
        </div>
        </Link>
    );
}
 
export default Model;

In my singleModel.js component that gets rendered when clicked (goal is to save the info in the state):

    const SingleModel = (props) => {
    const [single, setSingle]= useState(null)
    useEffect(()=> {
        let gender = props.location.state.gender;
        let name = props.location.state.name;
        console.log(gender);
        axios.get(`https://MYFIREBASEURL.com/Models/${gender}/${name}.json`)
            .then(response => {
                setSingle(response.data);
                console.log(response.data);
            })
            .catch((error)=> {
                console.log(error);
            });

        
    }, [props]);

    return (  
        <div className="singleModel">
            
        </div>
    );
}
 
export default SingleModel;

Try using the render method on the route:

<Route path='/women/:id' exact render={() => <SingleModel props={someprops}/>}></Route>

more on the router render method in the docs: https://reactrouter.com/web/api/Route/render-func

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