javascript - 在 React 中使用 Route 参数作为数组索引
问题描述
在我的App
组件中,我获取了一些关于组件挂载的数据,如下所示:
componentDidMount() {
axios.get("https://jsonplaceholder.typicode.com/posts?_limit=10")
.then(res => {
this.setState({
posts: res.data
});
});
}
在函数内部render
,我只想根据页面 ID将特定帖子作为道具传递:
<BrowserRouter>
<Route path="/about" component={About} />
<Route
path="/posts/:postId"
render={props => <Post {...props} post={this.state.posts[":postId"]} />}
/>
</BrowserRouter>
我想从我的Post
组件中访问特定的帖子,如下所示:
componentDidMount() {
this.setState({
id: this.props.match.params.postId,
post: this.props.post
});
}
但我无法使用this.props.post
. 显然,有问题的行是我尝试设置该帖子数据的地方:
render={props => <Post {...props} post={this.state.posts[":postId"]} />}
但是我不知道如何将发布数据作为属性传递给Post
组件。我刚刚开始学习 React,所以任何帮助将不胜感激。
解决方案
推荐阅读
- python - 无法使用 Python 和 PHPMyAdmin 将删除的表重新创建到任何 MySQL 数据库
- flutter - 颤振:FutureBuilder NoSuchMethodError isNotEmpty
- google-chrome - 在 Chromecast 上投射带有自动播放非静音视频的网页
- python - python json格式错误,“TypeError:字符串索引必须是整数”
- design-patterns - 使用捕获模式匹配来改变 Vec 元素
- python - 当我读取 .csv 表时,我的数据帧上有多个“\t”
- python - 有人可以向我解释为什么我的 django 管理主题是黑暗的吗?
- laravel - 如何在 laravel 5.5 中获取当前插入的行 ID
- css - jekyll 主题 CSS 在 github io 页面中不起作用
- http - 后缀日志:来自未知 IP 地址的非 SMTP 命令,“GET /aaa9 HTTP/1.1”