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

I'm sending an object with a couple of params through the "to" prop on my Link from reac

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745057758a4608772.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信