我试图将一个函数传递给一个React Router,但尽管进行了一些调整,但它给了我一个错误。我尝试将函数放在render()中,在params props之前添加了此函数,但似乎没有任何效果。如何在Route和Redirect标签之间传递函数以选择性返回?
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() {
let name = props.match.params.name;
let currDog = this.props.dogs.find(
dog => dog.name.toLowerCase() === name.toLowerCase()
);
if(currDog != undefined) {
return <DogDetails {...props} dog={currDog} /> ;
} else {
return <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()}} />
<Redirect to='/dogs' />
</Switch>
);
}
}
export default Routes;
我建议您分隔组件,因为可能会有很多路由,因此,您可能无法在一个组件中管理它们。
无论如何,请尝试将props作为参数发送给函数。
您应该使用BrowserRouter包装交换机。
import React, { Component } from 'react';
import { Switch, Route, Redirect, BrowserRouter as Router } 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) {
const { dogs } = this.props;
let name = props.match.params.name;
let currDog = dogs.find(
dog => dog.name.toLowerCase() === name.toLowerCase()
);
if(currDog != undefined) {
return <DogDetails {...props} dog={currDog} /> ;
} else {
return <Redirect to="/dogs" />
}
}
render() {
const { dogs } = this.props;
return(
<Router>
<Switch>
<Route exact path='/dogs' render= {() => <DogList dogs={dogs} />} />
<Route exact path='/dogs/:name' render={(props) => this.getDog(props)} />
<Redirect to='/dogs' />
</Switch>
</Router>
);
}
}
请记住,此反应路由器文档。这是一个很好的例子。https://reactrouter.com/web/guides/quick-start
这里有一个完整的例子。https://codesandbox.io/s/sleepy-ishizaka-n0433?file=/src/App.js
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句