React Router传递函数报错:'props'未定义,如何实现Route/Redirect切换返回?
解决React Router传递函数时的'props is not defined'错误
你的问题出在两个核心点上:一是getDog函数内部直接使用props但没有接收这个参数,导致未定义报错;二是在Route的render回调里调用this.getDog()时,既没传递路由props,也没返回函数执行结果(而render要求必须返回React元素)。
我帮你调整了代码,先看修改后的完整版本:
import React, { Component } from 'react'; import { Switch, Route, Redirect } from 'react-router-dom'; import DogList from './DogList'; import DogDetails from './DogDetails'; class Routes extends Component { constructor(props) { super(props); this.getDog = this.getDog.bind(this); } // 给getDog添加props参数,让函数能访问路由相关属性 getDog(props) { const name = props.match.params.name; const currDog = this.props.dogs.find(dog => dog.name.toLowerCase() === name.toLowerCase()); // 简化判断逻辑,undefined会被自动转为false return currDog ? <DogDetails {...props} dog={currDog} /> : <Redirect to="/dogs" />; } render() { return( <Switch> <Route exact path='/dogs' render={() => <DogList dogs={this.props.dogs} />} /> {/* 将路由props传递给getDog,并返回函数执行结果 */} <Route exact path='/dogs/:name' render={(props) => this.getDog(props)} /> <Redirect to='/dogs' /> </Switch> ); } } export default Routes;
另外给你个小优化建议:可以把getDog改成箭头函数,这样就不用在constructor里手动绑定this了,代码会更简洁:
class Routes extends Component { // 箭头函数自动绑定this,省去constructor内的bind操作 getDog = (props) => { const name = props.match.params.name; const currDog = this.props.dogs.find(dog => dog.name.toLowerCase() === name.toLowerCase()); return currDog ? <DogDetails {...props} dog={currDog} /> : <Redirect to="/dogs" />; } render() { return( <Switch> <Route exact path='/dogs' render={() => <DogList dogs={this.props.dogs} />} /> <Route exact path='/dogs/:name' render={(props) => this.getDog(props)} /> <Redirect to='/dogs' /> </Switch> ); } }
这样修改后,就能正常根据路由参数判断返回DogDetails还是Redirect,也不会再出现props未定义的编译错误了。
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

