javascript - 如何从 React 项目的 API URL 中删除冒号 (:)
问题描述
我正在尝试使用动态 id 从 API 获取数据。我的路线路径中有冒号。调试问题后,我注意到冒号包含在链接中的 id 之前,因此获取请求失败。请问我该如何解决这个问题。我的意思是,我向 ap1.yoursite.com/:111 发送请求而不是 ap1.yoursite.com/111,这导致 fetch 对象保持为空。如何使冒号作为动态路径工作,但不干扰我的 URL?
//我的路线和 // 获取代码片段
const Main = props => (
<Switch>
<Route exact path="/" component={Goods} />
<Route path="/items:id" component={SingleGoods} />
</Switch>
);
const { id } = this.props.match.params;
console.log(id); //returns :number
fetch(`http://api.yoursite/${id}`)
.then(response => response.json())
.then(json => this.setState({ show: json }));
console.log(this.state.show); //always returns null, which is the initial state
解决方案
我不确定我是否理解正确,但我认为:
<Route path="/items:id" component={SingleGoods} />
应该
<Route path="/items/:id" component={SingleGoods} />
在路径中有另一个斜线。
推荐阅读
- amazon-web-services - S3 存储桶文件前缀
- javascript - 通过反应在音频标签上设置音量
- postgresql - 如何使用 pg_restore 在 cloudsql 中导入转储文件?
- python - 在python中运行一个pickle文件
- angular - 如何在 Angular 应用程序包升级后修复 date-fns 错误?
- javascript - Javascript,删除 jQuery 调用
- sql - 操作数数据类型 nvarchar 对 avg 运算符无效
- asynchronous - 异步调用短期密钥期间的加密密钥管理
- mysql - Mysql状态连接只用一次查询就增加了很多倍?
- python - 如何根据一列中每个月的计数来获取所有前(最大)月份