react-router-dom "No match 404" 在前往带有 "useParams" 的路径时得到渲染

react-router-dom "No match 404" get rendered when going to a path with "useParams"

我正在使用 react-router-dom 没有 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 prop 添加到你的其他路由以使它们更具体。

像这样:

{/* 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} />

勾选这个No Match (404)

或者你可以这样实现吗

这意味着如果上面的路由不匹配,唯一可能的解决方案是我们找到了一条实际上不存在的路由。

<Router>
  <Switch>
    <Route exact path="/" component={Hello} />
    <Route component={NotFound} />
  </Switch>
</Router>

假设您已将路由渲染到 Switch 组件中,那么您需要记住当 独占 matching/rendering 路由路径顺序和特异性很重要!这是因为 Switch 组件匹配并呈现 与位置匹配的 first<Route><Redirect>

Switch

<Switch> is unique in that it renders a route exclusively. In contrast, every <Route> that matches the location renders inclusively.

如果您首先列出不太具体的路径,它们将被匹配和呈现。您应该按照特异性的相反顺序对路径进行排序。如果做得正确,几乎* 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 属性用于主页 "/" 路径以防止它匹配任何其他非主页组件。