我必须在子组件中使用 fetch,但我不知道如何在 Route 中发送 props。有什么选择可以做到这一点还是我必须以其他方式做到这一点?
这是我的父组件中的路由:
<Route path={`/beers/:beerId`} component={Beer}/>
然后我想在子组件中使用 fetch:
fetchData = () => {
let url = `https://api.punkapi.com/v2/beers/${this.props.id}`;
fetch(url, {method: 'get'}).then(resp => resp.json()).then((data) =>
this.setState({
data: data
})
);
};
最佳答案
当Route
匹配时,它将向它所持有的组件注入(inject)三个 Prop :
位置
:有关当前位置的信息。历史记录
:访问浏览器历史记录和导航方法。match
:所有匹配的网址参数。
因此,在您的 Beer
组件中,您可以使用 match.params.beerId
访问 URL 参数 beerId
,并且您的 Ajax 调用:
const {beerId} = this.props.match.params;
fetchData = () => {
let url = `https://api.punkapi.com/v2/beers/${beerId}`;
fetch(url, {method: 'get'}).then(resp => resp.json()).then((data) =>
this.setState({
data: data
})
);
}
关于javascript - 如何在 React Router v4 中向子进程发送 props?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54502305/