React+Redux -未捕获错误:期望reducer是一个函数

llmtgqce  于 2023-06-23  发布在  React
关注(0)|答案(8)|浏览(103)

我尝试了简单的react,redux, AJAX 工作示例,并遵循Reddit API tutorial,但我无法创建store和get错误:

Uncaught Error: Expected the reducer to be a function.

index.jsx

...

import { createStore, applyMiddleware } from 'redux'
var thunkMiddleware = require('redux-thunk');
var createLogger = require('redux-logger');
var rootReducer = require('./reducers.js');

        const loggerMiddleware = createLogger();

        function configureStore(initialState) {
            return createStore(
                rootReducer,
                initialState,
                applyMiddleware(
                    thunkMiddleware,
                    loggerMiddleware
                )
            )
        }

        const store = configureStore();

...

rootReducer.js

import { combineReducers } from 'redux';

function products(state = {
    isFetching: false,
    didInvalidate: false,
    items: []
}, action) {
    switch (action.type) {
        case 'REQUEST_PRODUCTS':
            return Object.assign({}, state, {
                isFetching: true,
                didInvalidate: false
            })
        case 'RECEIVE_PRODUCTS':
            return Object.assign({}, state, {
                isFetching: false,
                didInvalidate: false,
                items: action.posts,
                lastUpdated: action.receivedAt
            })
        default:
            return state
    }
}

function specialPosts(state = { }, action) {
    switch (action.type) {
        case RECEIVE_SPECPOSTS:
        case REQUEST_SPECPOSTS:
            return Object.assign({}, state, {
                req: true
            })
        default:
            return state
    }
}

const rootReducer = combineReducers({
    products,
    specialPosts
});

export default rootReducer;

rootReducer的类型是object,但为什么呢?我应该将createStore函数更改为rootReducer.default吗?

return createStore(
    rootReducer.default,
    initialState,
    applyMiddleware(
        thunkMiddleware,
        loggerMiddleware
     )
)

package.json

"redux-logger": "^2.6.1",
"react-redux": "^4.4.1",
"react-redux-provide": "^5.2.3",
"redux": "^3.3.1",
"redux-thunk": "^2.0.1",
9o685dep

9o685dep1#

const rootReducer = combineReducers({
    products,
    specialPosts
});

const store = createStore( rootReducer, applyMiddleware( thunkMiddleware ));

然后,初始状态将从各个reducer函数返回的初始状态自动创建。这些单独的状态可以作为state.productsstate.specialPosts访问

z9gpfhce

z9gpfhce2#

问题是由于rootReducer被“require”(ES5)导入:

var rootReducer = require('./reducers.js');

如果你通过ES6方法导入它,它会像你所期望的那样正确地将rootReducer.js的默认值自动保存到rootReducer中:

import rootReducer from './reducers';

我看到你在那个文件中混合了ES5(require)和ES6(import)...我在我的项目中也混合了,这就是为什么我遇到了这个问题。更多信息可以在这里找到:https://medium.com/@kentcdodds/misunderstanding-es6-modules-upgrading-babel-tears-and-a-solution-ad2d5ab93ce0#.2x2p2dx3m

kgqe7b3p

kgqe7b3p3#

创建存储时,第一个参数必须是函数,表示reduce(()=>[])参数

错误:

import {createStore,applyMiddleware} from 'redux';

export default function configureStore(initialState) {
  return createStore(
    [],
    {},
    applyMiddleware()
  );
}

解决方案:

import {createStore,applyMiddleware} from 'redux';

export default function configureStore(initialState) {
  return createStore(
    ()=>[],
    {},
    applyMiddleware()
  );
}
vojdkbi0

vojdkbi04#

当您看到错误时:
未捕获错误:期望reducer是一个函数
这并不一定意味着reducer不是一个函数。如果您遇到此错误,您应该尝试使用justreducer创建存储。就像这样:
createStore(reducer)
这可能是工作。
在我的例子中,第二个参数是错误的,因为我没有以正确的顺序调用composeapplyMiddleware。所以这是一个正确的设置,似乎在我的情况下工作:

export const createDebugStore = () => {
    const options: EnhancerOptions = {}
    const composeFunc = (typeof window !== 'undefined' && composeWithDevTools(options)) || compose;
    const enhancer = composeFunc(applyMiddleware());

    return createStore((state: any) => state || {}, enhancer);
}
fcipmucu

fcipmucu5#

rootReducer

/* index.js */

import AppReducer from './reducers';
// import {AppReducer} from './reducers';
// bugs : must be a root reducer, can not be use as a module






/* reducers.js */ 

// initial state
const initialState = {
    angular: 0,
    react: 0,
    vuejs: 0
};

// reducers update state 
const AppReducers = (state = initialState, action) => {
    switch (action.type) {
        case 'VOTE_ANGULAR':
            console.log("Vote Angular!");
            return (
                Object.assign(
                    {}, 
                    state, 
                    {
                        angular: state.angular + 1
                    }
                )
            );
        case 'VOTE_REACT':
            console.log("Vote React!");
            return (
                Object.assign(
                    {}, 
                    state, 
                    {
                        react: state.react + 1
                    }
                )
            );
        case 'VOTE_VUEJS':
            console.log("Vote Vue.jsc!");
            return (
                Object.assign(
                    {}, 
                    state, 
                    {
                        vuejs: state.vuejs + 1
                    }
                )
            );
        default:
            return state;
    }
};

export {AppReducers};
export default AppReducers;
vtwuwzda

vtwuwzda6#

我使用VS Code Insiders,有时更改无法正确保存。因此,如果您遵循了以上所有的操作,错误仍然存在,请转到每个文件并按STRG+S。它为我解决了这个问题。

vxbzzdmp

vxbzzdmp7#

我也遇到过同样的问题,它通过

const redux = require('redux');
const store = redux.createStore(reducer);

我的reducer

const reducer = (state = initailState, action)=>{
    if(action.type === 'BUY_CAKE'){

        return {...state, numOfCake : state.numOfCake + 1}
    }
    if(action.type === BUY_ICECREAM){

        return {...state, numOfIceCream : state.numOfIceCream + 1}
    }
}
x8goxv8g

x8goxv8g8#

当你看到这个错误:Uncaught Error: Expected the reducer to be a function时,必须确保在src/index.js文件中,createStore()方法的第二个参数必须是函数。
这是错误的:const store = createStore(rootReducer, applyMiddleware)
此分类下一篇:const store = createStore(rootReducer, applyMiddleware())

新更新请使用configureStore:

此分类下一篇:const store = configureStore(rootReducer, applyMiddleware())

相关问题