首页 > 解决方案 > 在 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,所以任何帮助将不胜感激。

标签: javascriptreactjsreact-router

解决方案


推荐阅读