我是一個龐大的系統工程工作的主要路線之前,我有一個授權系統,其中已登錄用戶可以訪問某些航線而未找到組件,在服務已註銷用戶。問題是,當用戶被標記爲登錄,並具有有效的標記,然後進行到頁面(例如/帳戶),組分未找到呈現第一和第二以後的部件帳戶呈現正確。陣營路由器*找不到*第一渲染
我有一個異步componentDidMount哪裏驗證我的令牌,如果它是有效的,我設置isLogged的狀態:真正。同樣在我的交換機中的每條路由上,我正在檢查isLogged的狀態,然後才發送相應的組件。
我的異步componentDidMount
{/* Username is from localstorage */}
async componentDidMount() {
if ((USERNAME != "") && (USERNAME != null)) {
const logged = await checkTheToken({'Username': USERNAME}).then((result) => {
if(result.status == 202) {
this.setState({isLogged: true});
this.setState({checking: false});
};
});
}
}
這是路由器(*假設我們正在試圖訪問/用戶頁面。請注意,我用的反應路由器,反應路由器-DOM^4.1 0.1 *)
if (this.state.checking) {
return null;
} else {
return (
<Router>
<Switch>
{/* This is Not Rendered First and Not Found rendered before FALSLY */}
{this.state.isLogged && <Route exact path="/user" component={() => (<User isLogged={this.state.isLogged} username={USERNAME} />)} />}
{/* This is Rendered First and Not Found is not rendering at all CORRECTLY */}
<Route exact path="/test" component={() => (<Test isLogged={this.state.isLogged} />)} />
<Route component={() => (<NotFound isLogged={this.state.isLogged} />)} />
</Switch>
</Router>
);
我認爲這個問題是在{this.state.isLogged & & ...},因爲如果我們嘗試訪問/test組件正確呈現沒有未找到先渲染。
另外,我測試了所有的生命週期方法
您是否嘗試過在'componentWillMount'中進行身份驗證檢查,您的組件在它進入'componentDidMount'之前已經進行了渲染。 – Purgatory
我測試了所有的生命週期方法 –
您可能需要添加一個狀態字段,比如'checking「,默認爲'true'。當你得到一個響應時,成功或錯誤會將'checking'設置爲'false'。在你的render中if(this.state.checking)返回null;'。 – Purgatory