this.props.history.push 在某些组件中有效,在其他组件中无效

this.props.history.push works in some components and not others

我正在尝试使用 browserHistory.push 以编程方式更改页面。在我的一个组件中,但不在我嵌入其中的组件中。

有谁知道为什么我的项目只针对子组件而不是父组件抛出下面的错误?

Cannot read property 'push' of undefined

父组件

import React, {Component} from 'react';
import { browserHistory } from 'react-router';
import ChildView from './ChildView';

class ParentView extends Component {

constructor(props) {
    super(props);
    this.addEvent = this.addEvent.bind(this);
  }

changePage() {
    this.props.history.push("/someNewPage");
  }

render() {
    return (
      <div>
        <div>
          <button onClick={this.changePage}>Go to a New Page!</button>
        </div>

        <ChildView />  // this is the child component where this.props.history.push doesn't work 

      </div>
    );
  }
}

function mapStateToProps(state) {
    return {
        user: state.user
    };
}

function matchDispatchToProps(dispatch) {
    return bindActionCreators({
      setName: setName
    }, dispatch)
}

export default connect(mapStateToProps, matchDispatchToProps)(ParentView);

子组件

    import React, {Component} from 'react';
    import { browserHistory } from 'react-router';

    class ChildView extends Component {

    constructor(props) {
        super(props);
        this.addEvent = this.addEvent.bind(this);
      }

    changePage() {
        this.props.history.push("/someNewPage");
      }

    render() {
        return (
          <div>
            <div>
              <button onClick={this.changePage}>Go to a New Page!</button>
            </div>

          </div>
        );
      }
    }

    function mapStateToProps(state) {
        return {
            user: state.user
        };
    }

    function matchDispatchToProps(dispatch) {
        return bindActionCreators({
          setName: setName
        }, dispatch)
    }

    export default connect(mapStateToProps, matchDispatchToProps)(ChildView);

路由器

// Libraries
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { browserHistory } from 'react-router';

// Components
import NotFound from './components/NotFound';
import ParentView from './components/ParentView';
import ChildView from './components/ChildView';
import SomeNewPage from './components/SomeNewPage';

// Redux
import { Provider } from 'react-redux';
import {createStore} from 'redux';
import allReducers from './reducers';

const store = createStore(
  allReducers,
  window.devToolsExtension && window.devToolsExtension()
);

const routes = (
    <Router history={browserHistory}>
      <div>
        <Provider store={store}>
            <Switch>
              <Route path="/" exact component={Home} />
              <Route path="/parentView" component={ParentView} />
              <Route path="/someNewPage" component={SomeNewPage} />
              <Route path="/childView" component={ChildView} />
              <Route component={NotFound} />
            </Switch>
        </Provider>
      </div>
    </Router>
);

export default routes;

如您所见,这些组件几乎完全相同,只是子组件在父组件内部。

请注意,我已经尝试过这些方法,但它们没有解决我的问题:

您在问题中回答了您的问题。

As you can see, the components are virtually exactly the same except that the child one is inside the parent one.

组件进一步嵌套这一事实本身就是您的问题。 React router 只将路由 props 注入它路由到的组件,而不注入嵌套在 in 中的组件。

查看 问题的已接受答案。基本思想是您现在需要找到一种方法将路由道具注入 child 组件。 您可以通过将 child 包装在 HOC withRouter.

中来实现
export default withRouter(connect(mapStateToProps, matchDispatchToProps)(ChildView));

希望对您有所帮助。

使用 withRouter 很好,另一种选择是将历史记录作为道具从 parent 传递到 child(不使用 withRouter),例如:

Parent

<SignupForm history={this.props.history}/>

Child

this.props.history.push('/dashboard');

这是嵌套组件的问题。 我在 Header 组件中遇到了这个问题。 我想在点击徽标时将页面重定向到主页。

this.props.history.push 在嵌套组件中不起作用。

所以解决方案是使用 withRouter .

要使用 withRouter 只需复制粘贴到页眉中的下面 2 行(您可以在您的组件中使用它):

import { withRouter } from "react-router";
export default withRouter(connect(mapStateToProps, {
    ...
})(Header));

你可以试试这个

this.context.history.push('/dashboard')

或将历史作为道具从 parent 传递到 child 组件,如

parent

<SignupForm history={this.props.history}/>

child

this.props.history.push('/dashboard');

withRouter

import { withRouter } from "react-router";
export default withRouter(connect(mapStateToProps, {
    ...
})(Header));

如果有人仍然面临类似问题,请尝试将 onClick 更改为此

onClick={() => this.props.history.push("/dashboard")}

此外,如果您在子组件中,请使用 <Redirect to="/dashboard"/> 组件