Не удалось найти "магазин", даже если рут завёрнут в Provider

У меня есть приложение SSR react-redux. Где у меня есть основной файл index.js, включая компонент App, завернутый в Provider.

Но если я попытаюсь использовать соединение в компоненте App, он выдаст эту ошибку:

Uncaught Invariant Violation: Could not find "store" in the context of "Connect(App)"

Я уже проверил эти решения, и ни одно из них не имеет отношения ко мне.

связанные 01

связанные 02

связанные 03

// index.js
import React from 'react';
import { Provider } from 'react-redux';
import App from './App';
import configureStore from './store/configureStore';

const store = configureStore();

const app = () => (
  <Provider store = {store}>
    <App />
  </Provider>
);

export default app;
// App.js
import React, { Component } from 'react'
import { connect } from 'react-redux'

class App extends Component {
  render() {
    return (
      ...
    );
  }
};

const mapStateToProps = state => {
  return state;
};

export default connect(mapStateToProps,{})(App);
// configureStore.js

import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import thunk from 'redux-thunk';
import login from './login/reducer.js';

const configureStore = () => {
  const rootReducer = combineReducers({
    login
  });

  const composeEnhancers =
    process.env.NODE_ENV !== 'production' && typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
      ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
      : compose;

  const store = createStore(rootReducer, {}, composeEnhancers(applyMiddleware(thunk)));
  return store;
};

export default configureStore;
// login/reducer.js

const initialState = { user: {} };

const currentUser = (state = initialState, action) => {
  const { type, payload } = action;
  switch (type) {
    default: {
      return state;
    }
  }
};

export default currentUser;

Вот полная ошибка из консоли браузера

Uncaught Invariant Violation: Could not find "store" in the context of "Connect(App)". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to Connect(App) in connect options.
    at invariant (http://localhost:3000/bundle.js:146050:15)
    at Connect.renderWrappedComponent (http://localhost:3000/bundle.js:51859:58)
    at Connect.indirectRenderWrappedComponent (http://localhost:3000/bundle.js:51855:21)
    at updateContextConsumer (http://localhost:3000/bundle.js:70185:938)
    at beginWork (http://localhost:3000/bundle.js:70212:2189)
    at performUnitOfWork (http://localhost:3000/bundle.js:70889:349)
    at workLoop (http://localhost:3000/bundle.js:70896:45)
    at HTMLUnknownElement.callCallback (http://localhost:3000/bundle.js:67381:102)
    at Object.invokeGuardedCallbackDev (http://localhost:3000/bundle.js:67401:45)
    at invokeGuardedCallback (http://localhost:3000/bundle.js:67417:126)
invariant @ bundle.js:146050
renderWrappedComponent @ bundle.js:51859
indirectRenderWrappedComponent @ bundle.js:51855
updateContextConsumer @ bundle.js:70185
beginWork @ bundle.js:70212
performUnitOfWork @ bundle.js:70889
workLoop @ bundle.js:70896
callCallback @ bundle.js:67381
invokeGuardedCallbackDev @ bundle.js:67401
invokeGuardedCallback @ bundle.js:67417
replayUnitOfWork @ bundle.js:70757
renderRoot @ bundle.js:70918
performWorkOnRoot @ bundle.js:71100
performWork @ bundle.js:71082
performSyncWork @ bundle.js:71080
requestWork @ bundle.js:71056
scheduleWork @ bundle.js:71002
scheduleRootUpdate @ bundle.js:71138
updateContainerAtExpirationTime @ bundle.js:71139
updateContainer @ bundle.js:71139
ReactRoot.render @ bundle.js:71169
(anonymous) @ bundle.js:71182
unbatchedUpdates @ bundle.js:71126
legacyRenderSubtreeIntoContainer @ bundle.js:71182
hydrate @ bundle.js:71185
(anonymous) @ bundle.js:57511
__webpack_require__ @ bundle.js:20
(anonymous) @ bundle.js:52705
__webpack_require__ @ bundle.js:20
(anonymous) @ bundle.js:63
(anonymous) @ bundle.js:66
bundle.js:67495 Warning: Did not expect server HTML to contain a <div> in <div>.
warningWithoutStack @ bundle.js:67495
warnForDeletedHydratableElement @ bundle.js:69163
didNotHydrateContainerInstance @ bundle.js:69265
deleteHydratableInstance @ bundle.js:69882
popHydrationState @ bundle.js:69912
completeWork @ bundle.js:70494
completeUnitOfWork @ bundle.js:70849
performUnitOfWork @ bundle.js:70895
workLoop @ bundle.js:70896
renderRoot @ bundle.js:70911
performWorkOnRoot @ bundle.js:71100
performWork @ bundle.js:71082
performSyncWork @ bundle.js:71080
requestWork @ bundle.js:71056
scheduleWork @ bundle.js:71002
scheduleRootUpdate @ bundle.js:71138
updateContainerAtExpirationTime @ bundle.js:71139
updateContainer @ bundle.js:71139
ReactRoot.render @ bundle.js:71169
(anonymous) @ bundle.js:71182
unbatchedUpdates @ bundle.js:71126
legacyRenderSubtreeIntoContainer @ bundle.js:71182
hydrate @ bundle.js:71185
(anonymous) @ bundle.js:57511
__webpack_require__ @ bundle.js:20
(anonymous) @ bundle.js:52705
__webpack_require__ @ bundle.js:20
(anonymous) @ bundle.js:63
(anonymous) @ bundle.js:66
bundle.js:70552 The above error occurred in the <Context.Consumer> component:
    in Connect(App)
    in Router (created by BrowserRouter)
    in BrowserRouter

Возможно, вы также можете опубликовать код для configureStore()

Clinton Chau 08.04.2019 06:22

@ClintonChau обновил вопрос, пожалуйста, проверьте сейчас. Спасибо!

Shubham Kushwah 08.04.2019 14:13
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Навигация по приложениям React: Исчерпывающее руководство по React Router
Навигация по приложениям React: Исчерпывающее руководство по React Router
React Router стала незаменимой библиотекой для создания одностраничных приложений с навигацией в React. В этой статье блога мы подробно рассмотрим...
Массив зависимостей в React
Массив зависимостей в React
Все о массиве Dependency и его связи с useEffect.
1
2
5 184
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Судя по трассировке стека, вы выполняете рендеринг App. Однако App обернут Provider внутри нового компонента, который вы создаете, под названием app. Таким образом, когда вы пытаетесь отрендерить App, react-redux правильно сообщает вам, что App не имеет связанного с ним store.

Например, вы должны написать это:

const MyAppWithStore = () => (
  <Provider store = {store}>
    <App />
  </Provider>
);

ReactDOM.render(<MyAppWithStore />, document.getElementById('root'));

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

Другие вопросы по теме