React store.getState 不是函数

IT技术 javascript reactjs redux-saga
2021-05-02 20:48:42

这是我的代码:

商店.js

import {createStore, applyMiddleware, compose} from 'redux';
import {fromJS} from 'immutable';
import {routerMiddleware} from 'react-router-redux';
import createSagaMiddleware from 'redux-saga';
import createReducer from './reducers';

const sagaMiddleware = createSagaMiddleware();

export default function configureStore(initialState = {}, history) {
    // Create the store with two middlewares
    // 1. sagaMiddleware: Makes redux-sagas work
    // 2. routerMiddleware: Syncs the location/URL path to the state
    const middlewares = [sagaMiddleware, routerMiddleware(history)];

    const enhancers = [applyMiddleware(...middlewares)];

    const store = createStore(createReducer, fromJS(initialState), enhancers);

    // Extensions
    store.runSaga = sagaMiddleware.run;
    store.asyncReducers = {}; // Async reducer registry

    return store;
}

路由.js

import React from 'react';
import {Route, Router, IndexRoute, browserHistory} from 'react-router';
import {syncHistoryWithStore} from 'react-router-redux';
import store from './store';

import Welcome from './containers/Welcome';

const history = syncHistoryWithStore(browserHistory, store);

const routes = (
    <Router history={history}>
        <Route path="/">
              <IndexRoute component={Welcome} />
        </Route>
    </Router>
);

export default routes;

索引.js

import React from 'react';
import ReactDOM from 'react-dom';
import {browserHistory} from 'react-router';
import { Providers } from 'react-redux';
import configureStore from './store';
import routes from './routes';


const initialState = {};
const store = configureStore(initialState, browserHistory);

ReactDOM.render(
    <Provider store={store}>
        {routes}
    </Provider>, document.getElementById('main-content')
);

我找不到罪魁祸首在哪里。我试图调试它,但找不到真正导致这些错误的原因。错误:未捕获的类型错误:store.getState 不是函数

有什么解决办法吗?

4个回答

这是一个产生错误的错字: TypeError: store.getState is not a function

错误的

const store = createStore(()=>[], {}, applyMiddleware);

正确的

const store = createStore(()=>[], {}, applyMiddleware());

请注意添加的括号()applyMiddleware

请注意,您Routes.jsstore未正确初始化。您应该添加以下几行:

  const initialState = {};
  const store = configureStore(initialState, browserHistory);

就像在您的index.js文件中一样。

希望它会有所帮助,但在我的情况下,我收到此错误,因为我的商店如下所示,这是一个功能:

 const store = preloadedState => {
    let initialState={}
    //some code to modify intialState
   
    return createStore(reducer, initialState)
}

但在 index.js 中,我将 store 作为函数传递,而不是它返回的值。

错误的

<Provider store={store}>
    <MyApp />
</Provider>

正确的

<Provider store={store()}>
    <MyApp />
</Provider>

我正在这样做(动态要求)..

    const store = require('../store/app')
    state = store.getState()

但是出于某种原因,在使用require而不是import您必须这样做时..

    const store = require('../store/app')
    state = store.default.getState()