2017-04-07 63 views
6

我已升級到React路由器V4,現在正在與history.push方法掙扎。ReactJS路由器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> 
    ) 
    } 
} 

所以,我無法弄清楚這裏出了什麼問題。當我點擊該按鈕時,URL更改爲/,但這就是全部。有人能幫助我嗎?

編輯

我發現,這當我這樣做的工作:

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

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

但似乎錯了不知何故?

當我做

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

我得到Cannot read property 'context' of null但爲什麼?我的<BrowserRouter>設置錯誤嗎?

無論如何,感謝您的幫助:)

+1

BrowserRouter在默認情況下具有隱式歷史記錄。你需要使用路由器。 參考:https://reacttraining.com/react-router/web/api/Router – Adriano

+0

[如何在React Router v4中推送歷史記錄?](https://stackoverflow.com/questions/42701129/)如何推動歷史在反應路由器v4) – lux

回答

2

你有導入{withRouter} from 'react-router-dom'並以這種方式導出您的課程

export default withRouter(Cars)

0

嘗試在您的BrowserRouter中添加forceRefresh = {true}。

<BrowserRouter forceRefresh={true}>