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 badges1 Answer
Reset to default 4You 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条)