【问题标题】:React nested route render the parent component with the child componentReact 嵌套路由用子组件渲染父组件
【发布时间】:2021-10-23 11:49:05
【问题描述】:

我正在学习 React(来自 ASP.NET)。当我转到'/employee' 时,它将显示员工列表。但是当我转到'/employee/create' 时,它会同时显示表格和创建表单。我到'/employee/create'时如何只显示创建员工表单?

export default class App extends Component {
static displayName = App.name;

render() {
    return (
        <Layout>
            <Route exact path='/' component={Home} />
            <Route path='/counter' component={Counter} />
            <AuthorizeRoute path='/fetch-data' component={FetchData} />
            <Route exact path='/employee' component={EmployeeIndex} />
            <Route path='/employee/create' component={EmployeeCreate} />
            <Route path='/employee/details/:id' component={EmployeeDetails} />
            
        </Layout>
    );
 }
}

【问题讨论】:

    标签: javascript reactjs routes react-router


    【解决方案1】:

    为此,您需要在您的 Routes 周围添加一个 &lt;Switch&gt;:

    import { Route, Switch } from "react-router";
    
    
    <Switch>
       <Route exact path='/' component={Home} />
       <Route path='/counter' component={Counter} />
       <AuthorizeRoute path='/fetch-data' component={FetchData} />
       <Route exact path='/employee' component={EmployeeIndex} />
       <Route path='/employee/create' component={EmployeeCreate} />
       <Route path='/employee/details/:id' component={EmployeeDetails} />
    </Switch>
    

    它就像一个普通的 `switch-case 一样工作,只会在你的 Routes 中呈现第一个匹配的路径。

    如果没有 &lt;Switch&gt;,它将呈现 ALL 匹配的路由。

    【讨论】:

    • 我必须将 &lt;Route exact path='/employee' component={EmployeeIndex} /&gt; 移到底部,在 &lt;/Switch&gt; 之前,才能使其正常工作。
    【解决方案2】:

    这是我在我的应用程序中使用的内容。 为所有页面制作单独的组件,并在 src 下的 App.js 中导入。利用 state 和 props 来存储数据并创建 ID。安装 npm i react-router-dom 以访问 react 路由。

    import { Switch, Route, Redirect } from "react-router-dom";
    <Switch>
        <Route exact path="/" component={Home} />
        <Route exact path="/employee" component={Employee} />
        <Route exact path="/createEmployee" component={Create} />
        <Route exact path="/employeeDetails" component={Details} />
        <Redirect to = "/" />   
    </Switch>
    
    1. 主页 - Home.js
    2. 用于员工列表 - Employee.js
    3. 创建员工 - Create.js
    4. 转到员工的详细信息 - Details.js
    5. 重定向到 - 如果未输入确切的 URL,将重定向到主页。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-24
      • 2017-04-20
      • 1970-01-01
      • 2018-11-17
      • 2016-06-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多