Javascript 如何在React项目中从API URL中删除冒号(:)
我正在尝试从API获取数据,具有动态id。我的路由路径中有冒号。调试该问题后,我注意到冒号包含在链接中id之前,因此获取请求失败。请告诉我如何解决这个问题。我的意思是,我不是向ap1.yoursite.com/111发送请求,而是向ap1.yoursite.com/:111发送请求,这导致fetch对象保持为null。如何使冒号作为动态路径工作,但不干扰我的URL //我的路线和//获取代码段Javascript 如何在React项目中从API URL中删除冒号(:),javascript,reactjs,react-router,Javascript,Reactjs,React Router,我正在尝试从API获取数据,具有动态id。我的路由路径中有冒号。调试该问题后,我注意到冒号包含在链接中id之前,因此获取请求失败。请告诉我如何解决这个问题。我的意思是,我不是向ap1.yoursite.com/111发送请求,而是向ap1.yoursite.com/:111发送请求,这导致fetch对象保持为null。如何使冒号作为动态路径工作,但不干扰我的URL //我的路线和//获取代码段 const Main = props => ( <Switch> <
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
const Main=props=>(
);
const{id}=this.props.match.params;
console.log(id)//返回:数字
取回(`http://api.yoursite/${id}`)
.then(response=>response.json())
.then(json=>this.setState({show:json}));
console.log(this.state.show)//始终返回null,这是初始状态
我不确定我是否理解正确,但我认为:
<Route path="/items:id" component={SingleGoods} />
应该是
<Route path="/items/:id" component={SingleGoods} />
在路径中使用另一个斜杠。尝试
,注意参数前面的“/”
您是否打算使用如下路径:
/items/11
然后使用此id
发出提取请求?如果是,则将第二条路线更改为:
<Route path="/items/:id" component={SingleGoods} />
因此,当您访问/items/11
时,您可以在SingleGoods
组件中使用此id
看:。我很笨。我怎么会犯这样一个简单的错误,并且已经调试了好几个小时的代码。谢谢。