React Router + Redux:历史未定义

时间:2017-12-16 22:48:45

标签: reactjs redux react-router

我有以下组件:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { logoutUser } from '../actions';

class NavBar extends Component {

  onLogoutClick() {
    this.props.logoutUser();
    this.props.history.push('/login'); // here is the issue
  }

  render() {
    return (
      <div>
        <button
          className="btn btn-danger pull-xs-right"
          onClick={this.onLogoutClick.bind(this)}
        >
          Logout
        </button>
      </div>
    );
  }
}

export default connect(null, {logoutUser})(NavBar);

我在控制台中收到此错误:

Cannot read property 'push' of undefined

为什么这个组件的道具中没有历史记录?

更新1

这是托管App.js的{​​{1}}:

BrowserRouter

这是PrivateRoute:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import promise from 'redux-promise';

import reducers from './reducers';

import LoginForm from './components/login_form';
import NavBar from './components/nav_bar';
import Homepage from './components/home_page';
import PrivateRoute from './components/private_route';

const createStoreWithMiddleware = applyMiddleware(promise)(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
      <BrowserRouter>
        <div>
          <PrivateRoute exact path="/" component={Homepage} />
          <Route exact path="/login" component={LoginForm} />
        </div>
      </BrowserRouter>
  </Provider>
  , document.querySelector('.container'));

import React from 'react'; import { Route, Redirect } from 'react-router-dom'; import Homepage from './home_page'; export const PrivateRoute = ({ component: Component, ...rest }) => ( <Route {...rest} render={props => ( <Component {...props} /> props.location } }} /> )} /> ) export default PrivateRoute;

Homepage.js

更新2

我还有 LoginForm 组件,它与前一个组件大致相同,但它运行正常:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import NavBar from './nav_bar';

export default class HomePage extends Component {
  render() {
    return (
      <div>
        <NavBar />
        <h1>Welcome to the homepage</h1>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:3)

您需要使用withRouter

装饰您的组件

例如。添加到顶部:

import { withRouter } from 'react-router';

并将导出更改为:

export default withRouter(connect(null, {logoutUser})(NavBar));

这将为您提供反应路由器道具。

请参阅https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md