亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

React Router 總是渲染 NotFound 默認組件

React Router 總是渲染 NotFound 默認組件

aluckdog 2023-06-15 09:44:43
我一直在互聯網上搜索解決方案,但可惜我來這里尋求幫助。問題是 URL 發生了變化,但是相應的組件沒有Route呈現,而是NotFoundPage呈現了。這是App.js Router代碼:<Router history={history}>   <Switch>     <PrivateRoute exact path="/" component={HomePage} />     <Route path="/login" component={LoginPage} />     <Route path="/register" component={RegisterPage} />     <Route component={NotFoundPage}/>   </Switch></Router>這是PrivateRoute代碼:import React from 'react';import { Route, Redirect } from 'react-router-dom';export const PrivateRoute = ({ component: Component, ...rest }) => (    <Route {...rest} render={props => (        localStorage.getItem('user')            ? <Component {...props} />            : <Redirect to={{ pathname: '/login', state: { from: props.location } }} />    )} />)我面臨的問題是,當我轉到/is NotFoundPagerendered 而不是LoginPage URL正確重定向并更改為/login. 但是當我刷新時,它LoginPage被渲染了。同樣,當我單擊/register從LoginPageURL 更改但RegisterPage不呈現它的鏈接時,它是相同的NotFoundPage。
查看完整描述

1 回答

?
哈士奇WWW

TA貢獻1799條經驗 獲得超6個贊

這種奇怪的行為源于使用自定義歷史記錄。

const?customHistory?=?createBrowserHistory();
ReactDOM.render(<Router?history={customHistory}?/>,?node);

當它被使用時,路由器不會對位置路徑的變化做出反應。直到你不添加:

<Switch?location={window.location}>

根據文檔,默認情況下 switch 中的位置設置為窗口。location 但出于某種原因,當您不使用 BroswerRouter 或 StackRouter 而只是 Router 時,當我們直接設置位置時,它開始工作。


查看完整回答
反對 回復 2023-06-15
  • 1 回答
  • 0 關注
  • 189 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號