javascript - Location prop undefined on refresh (ReactJS) - Stack Overflow

admin2025-04-19  0

I'm sending an object with a couple of params through the "to" prop on my Link from react-router-dom. Initially, when the link is clicked, the data is fine and the props have their value. Once I refresh they are undefined.

Heres the Link...

let newTo = {
     pathname: `/poke/${name}`,
    param1: name
}
const { name } = this.props;
<Link style={viewBtn} to={newTo}>View</Link>

Heres the route if it matters...

<Route path="/poke/:pokemon" ponent={PokeSummary} />

Heres the code on my other ponent receiving the prop...

    constructor(props) {
    super(props)
    this.state = {
        paramName: props.location.param1,
        pokemon: {
            id: 0,
            name: '',
        },
        isLoading: false
    }
}

ponentDidMount() {
    this.fetchData(this.state.paramName)
}

fetchData = (nameP) => {
    fetch(`/${nameP}`)
        .then(res => res.json())
        .then(data => this.setState({
            pokemon: {
                id: data.id,
                name: data.name,
            }
        }, () => {console.log(this.state.pokemon)}))
}

Thanks!

I'm sending an object with a couple of params through the "to" prop on my Link from react-router-dom. Initially, when the link is clicked, the data is fine and the props have their value. Once I refresh they are undefined.

Heres the Link...

let newTo = {
     pathname: `/poke/${name}`,
    param1: name
}
const { name } = this.props;
<Link style={viewBtn} to={newTo}>View</Link>

Heres the route if it matters...

<Route path="/poke/:pokemon" ponent={PokeSummary} />

Heres the code on my other ponent receiving the prop...

    constructor(props) {
    super(props)
    this.state = {
        paramName: props.location.param1,
        pokemon: {
            id: 0,
            name: '',
        },
        isLoading: false
    }
}

ponentDidMount() {
    this.fetchData(this.state.paramName)
}

fetchData = (nameP) => {
    fetch(`https://pokeapi.co/api/v2/pokemon/${nameP}`)
        .then(res => res.json())
        .then(data => this.setState({
            pokemon: {
                id: data.id,
                name: data.name,
            }
        }, () => {console.log(this.state.pokemon)}))
}

Thanks!

Share asked Oct 7, 2019 at 11:17 Jacob BroughtonJacob Broughton 4222 gold badges6 silver badges16 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

You could just use props.match.params.pokemon instead of passing the param like so, since if the user is not redirected through your link and navigates to the url directly, these internal states will not be available

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745057759a282505.html

最新回复(0)