我正在通过react-router-dom通过Link上的“ to”道具发送带有几个参数的对象。最初,单击链接时,数据很好,道具也有其价值。刷新后,它们是不确定的。
在此处链接...
let newTo = {
pathname: `/poke/${name}`,
param1: name
}
const { name } = this.props;
<Link style={viewBtn} to={newTo}>View</Link>
请在此处关注路线...
<Route path="/poke/:pokemon" component={PokeSummary} />
在其他接收道具的组件上找到代码...
constructor(props) {
super(props)
this.state = {
paramName: props.location.param1,
pokemon: {
id: 0,
name: '',
},
isLoading: false
}
}
componentDidMount() {
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)}))
}
谢谢!
答案 0 :(得分:2)
您可以仅使用props.match.params.pokemon
而不是像这样传递参数,因为如果用户未通过您的链接重定向并直接导航到url,则这些内部状态将不可用