首页 > 解决方案 > 如何从 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

标签: javascriptreactjsreact-router

解决方案


我不确定我是否理解正确,但我认为:

<Route path="/items:id" component={SingleGoods} />  

应该

<Route path="/items/:id" component={SingleGoods} /> 

在路径中有另一个斜线。


推荐阅读