为什么我的React Route即使使用精确的道具也无法使用?

时间:2019-10-24 07:02:57

标签: reactjs react-router-dom

在以下情况下,我有一个帖子列表。 如果您单击一个帖子,它将被路由到“ / posts / 1”。 但是,在下面的代码中,当我单击任何一个帖子时,我可以看到URL更改为“ / posts / 1”,但是页面立即路由回“ / posts”,我无法理解为什么。 不应该在第二个路由()中“精确”确定发送的是该路径吗?

// Blog Component
<Switch>
    <Route path="/new-post" component={NewPost} />
    <Route path="/posts" exact component={Posts} />
    <Redirect from="/" to="/posts" />
</Switch>

// Posts Component
class Posts extends Component {
    state = {
        posts: [],
        selectedPostId: null
    };

    componentWillMount() {
        axios.get('https://jsonplaceholder.typicode.com/posts/')
        .then((response) => {
            this.setState({ posts: response.data.slice(0, 4) });
        });
    }

    onPostSelected = (id) => {
        this.props.history.push( '/posts/' + id );
    }

    render() {
        let posts = this.state.posts.map((post) => {
            return (
                    // <Link to={'/' + post.id} key={post.id}>
                        <Post 
                            key={post.id} 
                            title={post.title} 
                            author={post.author}
                            onClicked={() => this.onPostSelected(post.id)}/>
                    // </Link>
                   )
        });
        return (
            <div>
                <section className="Posts">
                    {posts}
                </section>
                <Route path={this.props.match.url + '/:id'} exact component={FullPost} />
            </div>
        );
    }
}

export default Posts;

1 个答案:

答案 0 :(得分:1)

这里的问题是,您在顶层路由上已指定了确切的位置,即/Posts,因此内部嵌套路由将不匹配,而是将重定向到/Posts

<Switch>
    <Route path="/new-post" component={NewPost} />
    <Route path="/posts" component={Posts} />
    <Redirect from="/" to="/posts" />
</Switch>

/posts路由中删除确切的代码,您的代码将起作用。