【发布时间】: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