[英]How can I remove colon (:) from API URL in React project
我正在嘗試使用動態 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} />
路徑中的另一個斜線。
試試<Route path="/items/:id" component={SingleGoods} />
,注意參數前的“/”。
您是否打算使用類似這樣的路徑: /items/11
然后使用此id
發出 fetch 請求? 如果是,則將您的第二條Route
更改為:
<Route path="/items/:id" component={SingleGoods} />
因此,當您訪問/items/11
您可以在SingleGoods
組件中使用此 ID。
請參閱: 響應路由器 URL 參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.