проблема с подключением нескольких компонентов контейнера к хранилищу - PullRequest
0 голосов
/ 25 сентября 2019

У меня проблемы с подключением компонентов моего контейнера к хранилищу резервов, я не уверен, где именно должно происходить соединение, будь то компонент контейнера или компонент, который будет отправлять действие.в настоящее время мой index.js выглядит следующим образом

import React from "react";
import reactDOM from "react-dom";
import App from "./app.jsx";
import storeFactory from "./store";
import { Provider } from 'react-redux';

const store = storeFactory();
reactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("app")
);

В настоящее время функция фабрики моего магазина выглядит следующим образом

import rootReducer from "../reducers";
import { createStore, applyMiddleware } from "redux";
import { fetchProductInformation } from "../actions";

const storeData = {
  productInformation: {}
};

const storeFactory = (initialState = storeData) => {
  applyMiddleware(fetchProductInformation)(createStore)(
    rootReducer,
    localStorage["redux-store"]
      ? JSON.parse(localStorage["redux-store"])
      : storeData
  );
};

export default storeFactory;

мой компонент контейнера равен

import SearchBar from '../components/searchbar.jsx';
import Nutrients from "../components/Nutrients.jsx";
import { fetchProductInformation } from '../actions';
import { connect } from 'react-redux';

const newSearch = (props) => (
  <SearchBar
  className="searchbar searchbar_welcome"
  onNewProduct={( name ) => (props.fetchProductInformation(name))}
/>
)

const productInformation = (props) => {
  const { nutrients, name } = props;
  return nutrients.length > 1 ? 
  (
    <div>
      <newSearch />
      <h3>{name}</h3>
      <hr/>
      <Nutrients
        className="nutrientInformation"
        list={nutrients}
      />
    </div>
  )
  : null
}

const mapStateToProps = ({nutrients, name}) => ({
  nutrients,
  name
});

const mapDispatchToProps = dispatch => ({
  fetchProductInformation: name => {
    dispatch(fetchProductInformation(name))
  }
});

export const Search = connect(null, mapDispatchToProps)(newSearch);
export const productInfo = connect(mapStateToProps)(productInformation);

, когдая запускаю код, я получаю следующую ошибку

Provider.js:19 Uncaught TypeError: Cannot read property 'getState' of undefined
    at Provider.js:19
    at mountMemo (react-dom.development.js:15669)
    at Object.useMemo (react-dom.development.js:15891)
    at useMemo (react.development.js:1592)
    at Provider (Provider.js:18)
    at renderWithHooks (react-dom.development.js:15108)
    at mountIndeterminateComponent (react-dom.development.js:17342)
    at beginWork$1 (react-dom.development.js:18486)
    at HTMLUnknownElement.callCallback (react-dom.development.js:347)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:397)
react-dom.development.js:19814 The above error occurred in the <Provider> component:
    in Provider

Consider adding an error boundary to your tree to customize error handling behavior.
Visit react-error-boundaries to learn more about error boundaries.
Provider.js:19 Uncaught TypeError: Cannot read property 'getState' of undefined
    at Provider.js:19
    at mountMemo (react-dom.development.js:15669)
    at Object.useMemo (react-dom.development.js:15891)
    at useMemo (react.development.js:1592)
    at Provider (Provider.js:18)
    at renderWithHooks (react-dom.development.js:15108)
    at mountIndeterminateComponent (react-dom.development.js:17342)
    at beginWork$1 (react-dom.development.js:18486)
    at HTMLUnknownElement.callCallback (react-dom.development.js:347)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:397)

из показанных ошибок, я не знаю точно, что это за ошибка, так как кажется, что она исходит от provider.js ..

1 Ответ

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

в вашем коде есть какая-то ошибка.здесь фиксированный код.

import SearchBar from '../components/searchbar.jsx';
import Nutrients from "../components/Nutrients.jsx";
import { fetchProductInformation } from '../actions';
import { connect } from 'react-redux';

const newSearch = (props) => (
  <SearchBar
  className="searchbar searchbar_welcome"
  onNewProduct={( name ) => (props.fetchProductInformation(name))}
/>
)

const productInformation = (props) => {
  const { nutrients, name } = props;
  return nutrients.length > 1 ? 
  (
    <div>
      <newSearch />
      <h3>{name}</h3>
      <hr/>
      <Nutrients
        className="nutrientInformation"
        list={nutrients}
      />
    </div>
  )
  : null
}

const mapStateToProps = ({nutrients, name}) => ({
  nutrients,
  name
});

const mapDispatchToProps = dispatch => ({
  fetchProductInformation: name => {
    dispatch(fetchProductInformation(name))
  }
});

export const Search = connect(null, mapDispatchToProps)(newSearch);
export const productInfo = connect(mapStateToProps)(productInformation)

store.js

import rootReducer from "../reducers";
import { createStore } from "redux";

const storeData = {
  productInformation: {}
};

const initialStore = localStorage["redux-store"] ? JSON.parse(localStorage["redux-store"]) : storeData;

const store = createStore(rootReducer, initialStore);

export default store;

index.js

import store from "./store";
...
       <Provider store={store}>
...
...