javascript - 提供查询参数时显示 404 的反应查询字符串
问题描述
我是 React 的新手,并试图根据 http://localhost:3000/show?name=james之类的名称查询来呈现页面
所以我最初将路线添加为:
<BrowserRouter>
<Switch>
<Route path='*' component={ErrorComponent} />} />
<Route path="show(/:name)" name="name" component={Show}></Route>
</Switch>
</BrowserRouter>
然后我尝试渲染组件 Show 如下所示:
import React, { Component } from 'react';
import queryString from 'query-string';
class Show extends Component {
componentDidMount(){
console.log(this.props.location.search);
const values = queryString.parse(this.props.location.search);
console.log(values.name);
}
render() {
const { params } = this.props.match;
return <div>
<h4>About</h4>
<p>This is About page.</p>
{params.id ? <b>ID: {params.id}</b> : <i>ID is optional.</i>}
</div>
}
}
export default Show;
然后当我尝试显示页面时
http://localhost:3000/show?name=james
它总是显示 404。不确定我做错了哪一部分。任何帮助表示赞赏。我也在使用 react-router-dom 5.1.2 。谢谢。
解决方案
编辑:不敢相信我最初没有注意到这一点......
您需要将您的path="*"
路线放在底部,Switch
否则它将匹配所有内容,并且它下面的任何内容甚至都没有机会匹配,因为Switch
es 仅匹配一条路线。当然,确保您的路由路径设置正确(如下)的描述也适用。
<Switch>
<Route path="/show/:name?" component={ShowRouteParam} />
<Route path="*">ERROR 404</Route>
</Switch>
https://codesandbox.io/s/elated-browser-d0sew?file=/src/App.js
路由与查询参数不匹配。
“请注意:由 path-to-regexp 返回的 RegExp 旨在与路径名或主机名一起使用。它无法处理 URL 的查询字符串或片段。”
根据您的操作方式,您可以将 id 作为路由的可选部分,也可以将其作为普通查询参数
选项1:
<Route path="/show/:name?" component={Show}></Route>
零件:
import React, { Component } from 'react';
import queryString from 'query-string';
class Show extends Component {
componentDidMount(){
console.log(this.props.location.search);
const values = queryString.parse(this.props.location.search);
console.log(values.name);
}
render() {
const { params } = this.props.match;
return <div>
<h4>About</h4>
<p>This is About page.</p>
{params.name ? <b>ID: {params.name}</b> : <i>Name is optional.</i>}
</div>
}
}
export default Show;
选项 2:
<Route path="/show" component={Show}></Route>
零件:
import React, { Component } from 'react';
import queryString from 'query-string';
class Show extends Component {
componentDidMount(){
console.log(this.props.location.search);
const values = queryString.parse(this.props.location.search);
console.log(values.name);
}
render() {
const values = queryString.parse(this.props.location.search);
return <div>
<h4>About</h4>
<p>This is About page.</p>
{values.name ? <b>ID: {values.name}</b> : <i>Name is optional.</i>}
</div>
}
}
export default Show;
推荐阅读
- javascript - 无法在中间件中修改/附加请求
- android - OnCreate 从 onNewIntent 触发两次
- javascript - 如何停止和重置倒数计时器?
- java - Kafka 序列化器/反序列化器中的配置函数有什么作用?
- jquery - 使用 AJAX 请求访问 Microsoft Graph API 以获取 excel 数据
- javascript - WebView 上传照片不起作用 - AndroidX
- ios - 带有 iOS 13 摄像头权限问题的 iPhone 11 Pro Max
- javascript - 如何修改减法的javascript代码
- spring - 没有登录表单的 Spring Boot 安全性
- php - 寻找质因数 PHP