【问题标题】:How can I remove colon (:) from API URL in React project如何从 React 项目的 API URL 中删除冒号 (:)
【发布时间】:2018-12-30 22:19:19
【问题描述】:

我正在尝试使用动态 ID 从 API 获取数据。我的路线路径中有冒号。调试问题后,我注意到冒号包含在链接中的 id 之前,因此获取请求失败。请问我该如何解决这个问题。我的意思是,我不是 ap1.yoursite.com/111 而是向 ap1.yoursite.com/:111 发送请求,这导致 fetch 对象保持为空。如何使冒号作为动态路径工作,但不干扰我的 URL?

//我的路线和//获取sn-p

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

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

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

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

    应该是

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

    路径中有另一个斜线。

    【讨论】:

    • 我很笨。我怎么会犯这么简单的错误,并且已经调试了我的代码几个小时。谢谢。
    【解决方案2】:

    试试&lt;Route path="/items/:id" component={SingleGoods} /&gt;,注意参数前的'/'。

    react-router url params

    【讨论】:

      【解决方案3】:

      您是否打算使用类似这样的路径:/items/11 然后使用此id 发出获取请求?如果是,则将您的第二个 Route 更改为:

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

      所以当你访问/items/11 时,你可以在你的SingleGoods 组件中使用这个id。

      请参阅:React Router URL params

      【讨论】:

        猜你喜欢
        • 2020-08-01
        • 1970-01-01
        • 2017-11-07
        • 2016-07-24
        • 2017-08-10
        • 1970-01-01
        • 1970-01-01
        • 2018-04-11
        相关资源
        最近更新 更多