React Invalid hook call with Provider, даже если я не использую хуки - PullRequest
0 голосов
/ 13 июля 2020

Я работал над проектом последние пару месяцев без проблем, но сегодня внезапно я получаю следующую ошибку, когда пытаюсь загрузить свой сервер разработки.

Ошибка: недопустимый хук вызов. Хуки могут быть вызваны только внутри тела функционального компонента. Это может произойти по одной из следующих причин: у вас могут быть несовпадающие версии React и средства визуализации (например, React DOM) 2. Возможно, вы нарушаете правила хуков 3. У вас может быть несколько копий React в одном и том же app

Я немного покопался и думаю, что проблема в моем Провайдере, но я понятия не имею, почему, потому что я не использовал хуки. Я уже проверил, что у меня запущено только 1 приложение React.

App. js

import {BrowserRouter, Route, Switch} from 'react-router-dom'
import {ProtectedRoute} from './components/utils/protected-routes'
import { PersistGate } from 'redux-persist/integration/react'
import LandingPage from './components/landingPage'
import Index from './components/recipe/main/index'
import Register from './components/register/register'
import ViewRecipe from './components/recipe/view-recipe/index'
import CreateRecipe from './components/recipe/create-recipe/index'
import ResetPassword from './components/account/reset-password/index'
import Discover from './components/recipe/discover/index'

import {Provider} from 'react-redux'; //Wraps everything insider provider
import {store, persistor} from './store';


function App() {
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <BrowserRouter>
            <div className="App">
              <Switch>
                <Route exact path ="/" component={LandingPage} />
                <ProtectedRoute path ="/Home" component={Index} />
                <Route path ="/Register" component={Register} />
                <Route path ="/ViewRecipe/:recipeId" component={ViewRecipe} />
                <Route path ="/CreateRecipe" component={CreateRecipe} />
                <Route path ="/EditRecipe" component={CreateRecipe} />
                <Route path ="/ResetPassword" component={ResetPassword} />
                <Route path ="/Discover" component={Discover} />

                <Route  path ="/*" component={() => "Error 404 Page Not Found"} />
              </Switch>
            </div>
        </BrowserRouter>
      </PersistGate>
    </Provider>
  );
}

export default App; 

store. js

import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage' // defaults to localStorage for web
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';

const initialState = {};

const middleware = [thunk];

const persistConfig = {
    key: 'root',
    storage,
}

const persistedReducer = persistReducer(persistConfig, rootReducer)


const store = createStore(
    persistedReducer,
    //rootReducer, 
    //persistedStorage,
    initialState,
    compose(applyMiddleware(...middleware), window.__REDUX_DEVTOOLS_EXTENSION__&& window.__REDUX_DEVTOOLS_EXTENSION__()
));

const persistor = persistStore(store);

export {store, persistor};



Ниже полная ошибка в моей консоли

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
    at resolveDispatcher (react.development.js:1465)
    at useMemo (react.development.js:1520)
    at Provider (Provider.js:10)
    at renderWithHooks (react-dom.development.js:14803)
    at mountIndeterminateComponent (react-dom.development.js:17482)
    at beginWork (react-dom.development.js:18596)
    at HTMLUnknownElement.callCallback (react-dom.development.js:188)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
    at invokeGuardedCallback (react-dom.development.js:292)
    at beginWork$1 (react-dom.development.js:23203)
    at performUnitOfWork (react-dom.development.js:22154)
    at workLoopSync (react-dom.development.js:22130)
    at performSyncWorkOnRoot (react-dom.development.js:21756)
    at scheduleUpdateOnFiber (react-dom.development.js:21188)
    at updateContainer (react-dom.development.js:24373)
    at react-dom.development.js:24758
    at unbatchedUpdates (react-dom.development.js:21903)
    at legacyRenderSubtreeIntoContainer (react-dom.development.js:24757)
    at Object.render (react-dom.development.js:24840)
    at Module../src/index.js (index.js:8)
    at __webpack_require__ (bootstrap:784)
    at fn (bootstrap:150)
    at Object.1 (register.css?0d8b:45)
    at __webpack_require__ (bootstrap:784)
    at checkDeferredModules (bootstrap:45)
    at Array.webpackJsonpCallback [as push] (bootstrap:32)
    at main.chunk.js:1
index.js:1 The above error occurred in the <Provider> component:
    in Provider (at App.js:19)
    in App (at src/index.js:10)
    in StrictMode (at src/index.js:9)

Consider adding an error boundary to your tree to customize error handling behavior.
console.<computed> @ index.js:1
react-dom.development.js:22665 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
    at resolveDispatcher (react.development.js:1465)
    at useMemo (react.development.js:1520)
    at Provider (Provider.js:10)
    at renderWithHooks (react-dom.development.js:14803)
    at mountIndeterminateComponent (react-dom.development.js:17482)
    at beginWork (react-dom.development.js:18596)
    at HTMLUnknownElement.callCallback (react-dom.development.js:188)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
    at invokeGuardedCallback (react-dom.development.js:292)
    at beginWork$1 (react-dom.development.js:23203)
    at performUnitOfWork (react-dom.development.js:22154)
    at workLoopSync (react-dom.development.js:22130)
    at performSyncWorkOnRoot (react-dom.development.js:21756)
    at scheduleUpdateOnFiber (react-dom.development.js:21188)
    at updateContainer (react-dom.development.js:24373)
    at react-dom.development.js:24758
    at unbatchedUpdates (react-dom.development.js:21903)
    at legacyRenderSubtreeIntoContainer (react-dom.development.js:24757)
    at Object.render (react-dom.development.js:24840)
    at Module../src/index.js (index.js:8)
    at __webpack_require__ (bootstrap:784)
    at fn (bootstrap:150)
    at Object.1 (register.css?0d8b:45)
    at __webpack_require__ (bootstrap:784)
    at checkDeferredModules (bootstrap:45)
    at Array.webpackJsonpCallback [as push] (bootstrap:32)
    at main.chunk.js:1


1 Ответ

0 голосов
/ 03 сентября 2020

Вам нужно будет сделать две вещи:

  1. Первая очистка кеша npm cache clear или npm cache clear --force
  2. В случае у вас есть предыдущая папка node_modules с именем node_modules1 не удалена. Удалите папку node_modules1 .

И начните заново npm start.

Надеюсь, это решит проблему.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...