离开页面时反应路由器回调

时间:2018-04-18 08:58:14

标签: reactjs react-router

我想知道用户是否要离开页面

我试过了:

componentWillMount() {
  this.props.router.setRouteLeaveHook(
    this.props.route,
    this.routerWillLeave
  )
},

但我明白了:

  

this.props.router未定义

我看到了一些解决方案,但我不想用这种反应方式:

React.createClass

react-router的版本:

"react-dom": "^16.3.1",
"react-router-dom": "^4.2.2",

我是如何实现路由器的:

root.jsx

import React from 'react'
import ReactDOM from 'react-dom'
import { App } from '../components/app'
import { BrowserRouter } from 'react-router-dom'

// Render component with data
document.addEventListener('DOMContentLoaded', () => {

    const node = document.getElementById('app');

    ReactDOM.render(
        (<BrowserRouter>
            <App />
        </BrowserRouter>),
        node )
});

app.jsx

import React from 'react'

import CompanyList from './company/company_list'
import CompanyDetails from './company/company_details'
import { CompanyNew } from "./company/company_new";
import { Error404 } from "./common/error_404";

import { Route, Switch } from 'react-router-dom'

export const App = () => {
    return (
        <Switch>
            <Route path='/' exact component={CompanyList}/>
            <Route path='/companies' component={CompanyList}/>
            <Route path='/company/new' component={CompanyNew}/>
            <Route path='/company/:id' component={CompanyDetails}/>
            /* 404 if not found : */
            <Route component={Error404}/>
        </Switch>
    )
};

编辑:

我尝试过:

import { withRouter } from 'react-router'

class CompanyDetails extends React.Component {

    constructor(props) {
        super(props);
    }

    componentWillMount() {
        this.props.router.setRouteLeaveHook(
            this.props.route,
            this.routerWillLeave
        )
    }
}

export default withRouter(CompanyDetails)

但我得到同样的错误

1 个答案:

答案 0 :(得分:1)

您可以从上下文中获取历史记录或在路由器外部创建历史记录并将其作为历史记录传递。