我是使用 react-router 的初学者,并且也会做出反应。我有一条链接到“/items”的路线,它取决于查询字符串 ex。'items?item_id=156' 并显示项目的信息。我让它像那样工作,但如果用户只访问没有查询字符串的'/items',我想显示 404。
提前谢谢你们
我是使用 react-router 的初学者,并且也会做出反应。我有一条链接到“/items”的路线,它取决于查询字符串 ex。'items?item_id=156' 并显示项目的信息。我让它像那样工作,但如果用户只访问没有查询字符串的'/items',我想显示 404。
提前谢谢你们
在这种情况下,您必须使用通配符匹配。您可以执行以下操作:
import React from 'react';
import { Switch } from 'react-router';
import { BrowserRouter , Route ) from 'react-router-dom;
import NotFound from './NotFound'
import ItemPage from './ItemPage'
const routes = ( import NotFound from './NotFound'
<BrowserRouter>
<Switch>
<Route path="*" component={NotFound}/>
<Route path="/items/:id/" component={ItemPage}/>
</Switch>
</BrowserRouter>
)
这假设您使用的是 react-router v4。
item_id
如果不可解析,您可以进行重定向。例如:
import queryString from 'query-string'
import { Redirect } from 'react-router-dom'
export default function Items() {
const queryValues = queryString.parse(this.props.location.search)
const itemId = queryValues['item_id']
if (isNaN(itemId)) {
return <Redirect to="/404.html" />
}
return ...
}