[英]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.