React Router:空白页

时间:2018-07-15 09:23:09

标签: reactjs react-router

这是我定义的路由器的方式:

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>的呈现。

问题 为什么第二条路由返回空白内容,而知道其组件的构造函数已被调用?为什么不处理渲染?

1 个答案:

答案 0 :(得分:0)

我尝试this.props.history.push('/ home');代码部分,但运行不正确。

您可以在下面看到我的组件代码。 我的完整组件代码:

onEdit(e)

仪表板组件代码:

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;