Не удается прочитать свойство 'forEach' из неопределенного в React - PullRequest
8 голосов
/ 30 сентября 2019

У меня есть следующий код, который я хочу использовать для проверки приватной маршрутизации:

import React from 'react';

import { Route, Redirect } from 'react-router-dom';
import routes from '../../routing/routes';

export default function PrivateRoute({ component: Component, ...rest }) {
    // TODO: user verification
    let user = 1;

    const authComponentResolver = props => {
        const authorizedComponent = <Component {...props} />
        const redirectToAuthComponent = <Redirect to={{ pathname: routes.login.path, state: { from: props.location } }} />

        if (user !== undefined) {
            return authorizedComponent;
        } else {
            return redirectToAuthComponent;
        }
    }

    return (
        <Route {...rest} render={authComponentResolver} />
    );
}

Но выдается следующая ошибка:

./src/components/auth/private-route.js
TypeError: Cannot read property 'forEach' of undefined

Я не могу понять, почему, носледующий код работает:

import React from 'react';

import { Route, Redirect } from 'react-router-dom';
import routes from '../../routing/routes';

export default function PrivateRoute(a) {
    // TODO: user verification
    let user = 1;

    const authComponentResolver = props => {
        const authorizedComponent = <a.component {...props} />
        const redirectToAuthComponent = <Redirect to={{ pathname: routes.login.path, state: { from: props.location } }} />

        if (user !== undefined) {
            return authorizedComponent;
        } else {
            return redirectToAuthComponent;
        }
    }

    return (
        <Route {...a} render={authComponentResolver} />
    );
}

Может кто-нибудь объяснить мне, почему не удается скомпилировать первую версию? Обе версии делают то же самое, я думаю.

Вот как я называю компонент:

const DashboardRoutes = () => (
    <Switch>
        <PrivateRoute exact path={routes.root.path} component={Dashboard} />
        <PrivateRoute path={routes.dashboard.path} component={Dashboard} />

        <PrivateRoute exact path={routes.persons.path} component={Persons} />
        <PrivateRoute path={routes.personsNew.path} component={NewPerson} />

        <PrivateRoute exact path={routes.branchOffice.path} component={BranchOffices} />
        <PrivateRoute path={routes.personsNew.path} component={NewPerson} />

        <PrivateRoute component={Error404} />
    </Switch >
);

В консоли у меня есть эта ошибка:

VM911 main.chunk.js:116 Uncaught Error: Module build failed (from ./node_modules/eslint-loader/dist/cjs.js):
TypeError: Cannot read property 'forEach' of undefined
    at Linter.parseResults (Users/groupon/Proyectos/Uselessscat/reservas-client/node_modules/eslint-loader/dist/Linter.js:121)
    at Linter.printOutput (Users/groupon/Proyectos/Uselessscat/reservas-client/node_modules/eslint-loader/dist/Linter.js:85)
    at cache (Users/groupon/Proyectos/Uselessscat/reservas-client/node_modules/eslint-loader/dist/cacheLoader.js:46)
    at Users/groupon/Proyectos/Uselessscat/reservas-client/node_modules/loader-fs-cache/index.js:122
    at Gunzip.cb (Users/groupon/Proyectos/Uselessscat/reservas-client/node_modules/loader-fs-cache/index.js:47)
    at Gunzip.zlibBufferOnEnd (zlib.js:131)
    at Gunzip.emit (events.js:203)
    at endReadableNT (_stream_readable.js:1145)
    at process._tickCallback (internal/process/next_tick.js:63)
    at Object../src/components/auth/private-route.js (VM911 main.chunk.js:116)
    at __webpack_require__ (VM909 bundle.js:786)
    at fn (VM909 bundle.js:151)
    at Module../src/routing/module-router.js (VM911 main.chunk.js:1098)
    at __webpack_require__ (VM909 bundle.js:786)
    at fn (VM909 bundle.js:151)
    at Module../src/routing/router.js (VM911 main.chunk.js:1226)
    at __webpack_require__ (VM909 bundle.js:786)
    at fn (VM909 bundle.js:151)
    at Module../src/index.js (VM911 main.chunk.js:787)
    at __webpack_require__ (VM909 bundle.js:786)
    at fn (VM909 bundle.js:151)
    at Object.0 (VM911 main.chunk.js:2552)
    at __webpack_require__ (VM909 bundle.js:786)
    at checkDeferredModules (VM909 bundle.js:46)
    at Array.webpackJsonpCallback [as push] (VM909 bundle.js:33)
    at VM911 main.chunk.js:1

ноэто неразборчиво: (

Спасибо.

Ответы [ 3 ]

1 голос
/ 02 октября 2019

Если вы используете react-scripts версию 3.1.2 или любую другую версию выше 3.0.1, вам может потребоваться понизиться до версии 3.0.1, так как она работает нормально. См. GitHub выпуск

1 голос
/ 30 сентября 2019

Похоже, eslint-loader ошибка сборки - пожалуйста, посмотрите на это . Попробуйте обновить до последней версии eslint-loader и тогда он должен работать. Если вы посмотрите на последнюю версию из Linter.js, вы увидите, что метод parseResults теперь имеет проверку if перед вызовом forEach.

0 голосов
/ 30 сентября 2019

Эта ошибка из eslint из react-scripts, поэтому мое решение отключено eslint.

  • Шаг 1: yarn add customize-cra react-app-rewired @babel/plugin-proposal-decorators --dev
  • Шаг 2: В файле config-overrides.js:
const { override, disableEsLint } = require("customize-cra");        
module.exports = override(
   disableEsLint()
);
  • Шаг 3: Обновить скрипт в файле package.json:
"scripts": {
  "start": "react-app-rewired start",
  "build": "react-app-rewired build"
},
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...