2017-09-19 68 views
0
componentDidMount() { 
    if (sessionStorage.loggedInUser === undefined && localStorage.loggedInUser === undefined) { 
     this.props.history.push("/"); 
    } 
    //Check if user owns the car to see if we should send the ajax 

    ajax.request.get("/cars/all").then((allCars) => { 

     this.setState({ 
      allCars: allCars 
     }) 
    }) 

} 

componentWillMount() { 
    if (sessionStorage.loggedInUser === undefined && localStorage.loggedInUser === undefined) { 
     this.props.history.push("/"); 
    } 
} 

後我有這樣的方法,i。由該代碼是通過槽他們調試看到,但重定向之後它進入到渲染方法,並開始執行它。爲什麼?Reactjs,渲染()被執行重定向

+0

你期待它由componentDidMount中移除,因爲要重定向但它仍然在後臺渲染頁面,這是你的意思? – johnjerrico

+0

是的,它仍然執行的渲染方法,並得到了一個未定義例外 – Alexander

+0

據我可以理解「推」不刪除舊頁,「替換」做 – johnjerrico

回答

1

一旦你開始安裝組件的過程中,它的生命週期方法都在排隊。在幕後,反應正在運行這些方法來生成「虛擬死亡」。即使結果永遠不會到達用戶,他們仍然需要執行內部目的的反應。

從事物的外表雖然看起來你想要的是中斷做出反應路由器頁面過渡,將用戶重定向到索引頁面的方式。這絕對是可能的,但componentDidMount掛鉤並不適合它。

你想要什麼onEnter鉤上反應路由器的路由組件,你可以用它來防止或重定向安裝過程開始之前。

這是(愚蠢)中除去從反應V4路由器,和社區是....不激動它。你的用例就是爲什麼它是一個必要的鉤子的完美例子,爲什麼我會建議堅持使用react-router的V3,直到這個鉤子恢復到當前版本。

+0

aha ok謝謝 – Alexander

1

我沒有測試過這一點,但我認爲你需要使用這種方法,而不是

this.history.replace("/")