以下是我定义的路由器:
import React from 'react';
import {BrowserRouter, Switch, Route} from 'react-router-dom';
import PersonsList from './PersonsList';
import Error from './Error'
import Person from './Person'
const Router = () => (
<BrowserRouter>
<Switch>
<Route path="/persons" strict={false} component={PersonsList}/>
<Route path="/persons/:id" component={Person}/>
<Route component={Error}/>
</Switch>
</BrowserRouter>
);
export default Router;
第一条路线完美无缺。
问题是在PersonsList
,当我尝试到达/persons/:id
路线时,我得到一个空白页面。
这是我在PersonsList组件中用于重定向的代码:
static propTypes = {
history: PropTypes.object
};
handleRedirection = (aPerson) => {
this.props.history.push(`/persons/${aPerson.id}`);
}
...
{this.state.persons.map(aPerson => (
<React.Fragment key={aPerson.id}>
<div className="row" onClick={this.handleRedirection.bind(this,aPerson)}>
这是Person
组件:
import React from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router';
class Person extends React.Component {
static propTypes = {
match: PropTypes.object
};
constructor(props){
super(props);
console.log('the selected person : ' + this.props.match.params.id);
}
render(){
return(
<div>A person</div>
)
}
}
export default withRouter(Person);
我可以看到console.log
输出但没有渲染<div>A person</div>
。
问题为什么第二条路径返回一个空白内容,知道其组件的构造函数被调用?为什么不处理渲染?
我试试this.props.history.push('/ home');代码部分但运行不正确。
您可以在下面看到我的组件代码。我的完整组件代码:
class Full extends Component {
render() {
return (
<div className="app">
<Header/>
<div className="app-body">
<Sidebar {...this.props}/>
<main className="main">
<Breadcrumb/>
<Container fluid>
<Switch>
<Route path="/dashboard" name="Dashboard" component={Dashboard}/>
<Route path="/applications" name="Applications" component={Applications}/>
<Route path="/roles" name="Roles" component={Roles}/>
<Route path="/poc" name="poc" component={Poc}/>
<Redirect from="/home" to="/dashboard"/>
</Switch>
</Container>
</main>
<Aside/>
</div>
<Footer/>
</div>
);
}
}
仪表板组件代码:
class Dashboard extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="animated fadeIn">
<div>test</div>
</div>
)
}
}
export default Dashboard;
历史代码:
import {createBrowserHistory} from 'history';
export const history = createBrowserHistory();