ReactJS Router V4 history.push无效

时间:2017-04-07 13:15:21

标签: reactjs react-router react-router-v4

我已升级到React Router V4,现在正在努力使用history.push方法。

我有一个index.js文件:

import React from "react";
import { render } from "react-dom";
import { BrowserRouter, Route } from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory';

const history = createBrowserHistory();

import { Main} from "./components/Main";
import { About } from "./components/About";
import { Cars} from "./components/Cars";


class App extends React.Component {

render() {
    return (
        <BrowserRouter history={history}>

            <div>
                <Route path={"/"} component={Main} />
                <Route path={"/cars"} component={Cars}/>
                <Route path={"/about"} component={About}/>
            </div>
        </BrowserRouter>
    )
  }
}

render(<App/>, window.document.getElementById("app"));

然后我有另一个文件,在那里我添加了一个简单的返回到某个页面,如下所示:

import React from "react";
import createBrowserHistory from 'history/createBrowserHistory';

const history = createBrowserHistory();

export class Cars extends React.Component {
  navigateBack() {
    history.push('/')
  }

  render() {
    return(
        <div>
            <h3>Overview of Cars</h3>
            <p>Model: </p>
            <button onClick={this.navigateBack} className="btn btn-primary">Back</button>
        </div>
    )
  }
}

所以,我无法弄清楚这里出了什么问题。当我点击按钮时,网址会更改为/,但这就是全部。有人可以帮助我吗?

修改

我发现,当我这样做时它会起作用:

this.props.history.push('/home')

<button onClick={this.onNavigateHome.bind(this)}

但似乎不知何故?

当我做的时候

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

我得到Cannot read property 'context' of null,但为什么?我的<BrowserRouter>设置错了吗?

无论如何,感谢您的帮助:)

5 个答案:

答案 0 :(得分:8)

您必须导入{withRouter} from 'react-router-dom'并以这种方式导出您的课程

export default withRouter(Cars)

答案 1 :(得分:1)

使用v4,您必须使用this.context.history.push('/cart');
查看这些帖子以获取更多见解:

How to push to History in React Router v4?

history.push not working when using BrowserRouter

答案 2 :(得分:0)

尝试将forceRefresh = {true}添加到您的BrowserRouter。

<BrowserRouter forceRefresh={true}>

答案 3 :(得分:0)

这对我有用:

routes.js

import React from 'react';
import { Route, Switch, Redirect } from 'react-router';
import { BrowserRouter } from 'react-router-dom';

const routes = (
  <div>
    <BrowserRouter>
      <Switch>
        <Route path="/login" component={Login} />
        <Route path="/home" component={Logged} />
      </Switch>
    </BrowserRouter>
  </div>
);

Login.js

componentWillReceiveProps = nextProps => {
    const { signedIn, history } = this.props;
    if (signedIn !== nextProps.signedIn && nextProps.signedIn) {
      history.push('/home');
    }
  };
export default withRouter(connect(mapStateToProps)(Login));

现在它将呈现!希望对别人有帮助

答案 4 :(得分:0)

尝试使用 props 中的历史记录并确保您的导出使用 withRouter 包装。

例如:

this.props.history.push('/test')


export default withRouter(TestComponent)