[英]react-router-dom "No match 404" get rendered when going to a path with "useParams"
我正在使用 react-router-dom No Match404 並且它工作正常但是當使用 useParams 進入路徑 a 時,它會呈現 404 頁面,代碼如下:
{/* Here it works fine it renders the routes */}
<Route path='/' exact component={Home} />
<Route path='/help' component={Help} />
<Route path='/signup' component={Signup} />
{/* The 404 page that render when a path does not exists */}
<Route component={Page404} />
{/* but when I try to render the route with useParams which is the uid I get from firebase it just render the Page404 */}
<Route path='/user/:uid' component={Profile} />
{/*-----------------Profile page------------------------*/}
// heres the profile page that uses useParams
import { useParams} from 'react-router-dom'
import {auth} from './firebase/config'
function Profile() {
let { uid } = useParams();
// here I have a variable that get a signed in user Unique Id from firebase
const [userId, setUserId] = useState('')
auth.onAuthStateChanged((user) => {
if (user) {
// User logged in already or has just logged in.
setUserId(user.uid);
} else {
// User not logged in or has just logged out.
}
});
if (uid === userId ) {
return <div>This is your profile</div>
}else{
return <div>This is someone elses or it does not exist</div>
}
}
當我刪除 404 路由時,此代碼運行良好,但是當我放置它時,配置文件路由會呈現 404 頁面。
有沒有辦法擁有 404 頁面,但僅在路由實際不存在時才呈現。
例如,當您有像404
這樣的一般路徑時,您必須將exact
道具添加到您的其他路線以使它們更加具體。
像這樣:
{/* but when I try to render the route with useParams which is the uid I get from firebase it just render the Page404 */}
<Route exact path='/user/:uid' component={Profile} />
{/* The 404 page that render when a path does not exists */}
<Route component={Page404} />
選中此不匹配 (404)
或者你可以像這樣實現
這意味着如果上面的路線不匹配,唯一可能的解決方案是我們找到了一條實際上並不存在的路線。
<Router> <Switch> <Route exact path="/" component={Hello} /> <Route component={NotFound} /> </Switch> </Router>
假設您已將路由渲染到Switch
組件中,那么您需要記住,在專門匹配/渲染路由時,路由路徑順序和特異性很重要! 這是因為Switch
組件匹配並呈現與該位置匹配的第一個子<Route>
或<Redirect>
。
<Switch>
的獨特之處在於它專門渲染了一條路由。 相比之下,每個匹配位置的<Route>
都會以包含的方式呈現。
如果您首先列出不太具體的路徑,它們將被匹配和渲染。 您應該以特定性的相反順序對路徑進行排序。 如果正確完成,幾乎* 0% 的用例需要exact
道具(在包含匹配路由器中的路由時更有用)。
<Switch>
<Route path='/user/:uid' component={Profile} />
<Route path='/help' component={Help} />
<Route path='/signup' component={Signup} />
<Route path='/' exact component={Home} /> // *
<Route component={Page404} />
</Switch>
* 在主頁"/"
路徑上使用的exact
屬性,以防止它與任何其他非主頁組件匹配。
假設你有另一個塊 ex。 <Layout>
,確保不要在<Switch>
和<Route>
之間放置任何塊
<Switch>
<Layout>
<Route exact path="/" component={Hello} />
<Route component={NotFound} />
</Layout>
</Switch>
進入
<Layout>
<Switch>
<Route exact path="/" component={Hello} />
<Route component={NotFound} />
</Switch>
</Layout>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.