【问题标题】:How to manually render specific component and exclude others within specific route如何手动渲染特定组件并在特定路由中排除其他组件
【发布时间】:2017-09-29 04:50:40
【问题描述】:

我有HeaderFooter 组件,用于包围内部页面。

我还有一个Login组件,在用户未登录时出现。这个组件没有实现HeaderFooter组件。

问题是我无法阻止HeaderFooter 组件被Login 组件渲染。我不能排除 Login 组件单独渲染。

我尝试了Switch 标签,但没有成功。

import React, { Component } from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
import { connect } from 'react-redux';
import * as actions from '../actions';

import Header from "./Header";
import Footer from "./Footer";
import Login from "./Login";
import manageCategories from "./manageCategories";

class App extends Component {
    componentDidMount() {
        this.props.fetchUser();
    }
    render() {
        return (
            <div>
                <BrowserRouter>
                    <div>
                        <Route exact path="/login" component={Login} />
                        <Header />
                        <Route exact path="/manage-categories" component={manageCategories} />
                        <Footer />
                    </div>
                </BrowserRouter>
            </div>
        );
    }
}

export default connect(null, actions)(App);

【问题讨论】:

    标签: reactjs react-router react-router-v4 react-router-dom


    【解决方案1】:

    您应该添加一个与登录组件平行的新组件以包含HeaderFooter 组件。

    <Route path="/home" component={Layout}/>
    <Route exact path="/login" component={Login}/>
    

    和布局:

        render() {
            return <div>
                <Header />
                <Route exact path={this.props.match.path} component={Home} />
                <Route path={`${this.props.match.path}/manageCategories`} component={manageCategories} />
                <Route path={`${this.props.match.path}/other`} component={otherComponent} />
                <Footer />
            </div>
        }
    

    【讨论】:

    • 我在manageCategories 组件中实现了headerfooter。是对的吗?对每个新组件进行这种实现?
    • 您可以添加一个布局组件来分发需要headerfooter组件的嵌套路由器组件。不需要headerfooter的组件可以是并行路由器。
    • 好的,您的建议适用于布局,但表单“${this.props.match.path}/manage-categories} component={manageCategories} />”不起作用。
    • 对不起,&lt;Route path="/home" component={Layout}/&gt; 我添加了多余的exact,为嵌套路由器删除它。
    • 好的,路由现在可以工作了,但是'manageCategories'组件内的所有数据渲染都不再工作了,只是空白页。
    猜你喜欢
    • 2018-04-18
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2020-12-10
    相关资源
    最近更新 更多