【问题标题】:Multiple components getting rendered for single route with react-router v4?使用 react-router v4 为单个路由渲染多个组件?
【发布时间】:2019-04-10 16:04:04
【问题描述】:

所以,我想了解为什么在这种情况下同时呈现 2 条路线:

import React, { Component } from 'react';
import { Route, NavLink, Switch } from 'react-router-dom';

import './Blog.css';
import Posts from './Posts/Posts';
import NewPost from './NewPost/NewPost';
import FullPost from './FullPost/FullPost'

class Blog extends Component {
    render () {
        return (
            <div className="Blog">
                <header>
                    <nav>
                        <ul>
                            <li><NavLink to="/" exact>Home</NavLink></li> 
                            <li><NavLink to= "/new-post">New Post</NavLink></li>
                        </ul>
                    </nav>
                </header>
                <Route path="/" exact component={Posts} />
                <Route path="/new-post" exact  component={NewPost} />
                <Route path="/:id" exact component={FullPost} />
            </div>
        );
    }
}
export default Blog;

当我点击 New Post 而不是只看到 NewPost 组件 时,我还看到了 FullPost 组件。在这种情况下,我无法理解 /newpost 路径和 /:id 路径是如何相同的。我知道这个问题可以用 Switch 解决,但是我想了解为什么会发生这种情况。

【问题讨论】:

    标签: reactjs path routes react-router-dom


    【解决方案1】:

    这是因为,当您导航到 /new-post 时,两条路由路径正在匹配。当你写:path="/:id",id(一个可选的路由参数)可以是任何东西,一个数字,字符串等,所以 id 会变成/new-post,它也会渲染FullPost,这就是原因。

    解决方案是,使用react-router 中的Switch(它总是渲染第一个匹配路径的组件)来避免匹配多个路径,这样在路由路径匹配时只会渲染一个组件。像这样:

    <Switch>
      <Route path="/" exact component={Posts} />
      <Route path="/new-post" exact  component={NewPost} />
      <Route path="/:id" exact component={FullPost} />
    </Switch>
    

    【讨论】:

      【解决方案2】:

      您需要将您的路线放在一个组件中。开关只会渲染第一个匹配的路由。

      <Switch>
       <Route path="/" exact component={Posts} />
       <Route path="/new-post" exact  component={NewPost} />
       <Route path="/:id" exact component={FullPost} />
      </Switch>
      

      这个答案在How to prevent matching two routes with react-router v4?

      当您不使用 Switch 时,您会匹配两个路由,因为 /new-post 也被您的路由器视为 id 参数。

      【讨论】:

        猜你喜欢
        • 2018-10-18
        • 2019-04-12
        • 2018-06-06
        • 1970-01-01
        相关资源
        最近更新 更多