N
N
Nikita2020-10-15 19:32:43
React
Nikita, 2020-10-15 19:32:43

Why doesn't the Route component work when it's rendered in a loop?

main.routes.js

// роуты
import React from "react"
import {Switch, Route, Redirect} from "react-router-dom"
import NotFound from '../components/pages/status/404.page'
import Unauthorized from '../components/pages/status/401.page'
import { StorageContextConsumer } from "../context/storage"
import Access from "../components/etc/Access"

export default () => {
    return (
        <StorageContextConsumer>
            {context => (
                <Switch>
                    {
                        context.modules.map(module => (
                            /*
                                 module выглядит так
                                {
                                    uname: `desktop_module`,
                                    path: `/`,
                                    accessLevel: 1,
                                    Component: Page // импортированный компонент страницы
                                }
                             */
                            <Access requiredLevel={module.accessLevel} key={module.uname}>
                                <Route
                                    path={module.path}
                                    component={module.Component}
                                    exact
                                />
                            </Access>
                        ))
                    }
                    <Route path="/401" component={Unauthorized} exact />
                    <Route path="/404" component={NotFound} exact />
                    <Redirect to="/404" />
                </Switch>
            )}
        </StorageContextConsumer>
    )
}


What does it have to do with putting Route
<Route path="/401" component={Unauthorized} exact />
<Route path="/404" component={NotFound} exact />
<Redirect to="/404" />

before the loop, then everything works

---- added ----

If you use it without context and consumer, then everything works.

Access.js (access component)
import React from "react"
import { StorageContextConsumer } from "../../context/storage"

export default props => (
    <StorageContextConsumer>
        {context => <>
            {
                props.strict
                    ? context.userAccessLevel === props.requiredLevel && props.children
                    : context.userAccessLevel <= props.requiredLevel && props.children
            }
        </>}
    </StorageContextConsumer>
)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question