同时应用applyMiddleware(thunk)获取“无法将类作为函数调用”,在react js中

问题描述 投票:2回答:2

这是我的index.js文件代码 -

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
import { BrowserRouter as Router, Route } from 'react-router-dom'; 
import { Provider } from 'react-redux';
import thunk from 'react-thunk';
import { createStore, applyMiddleware } from 'redux';
import Login from './Components/LoginRegister';

const store= createStore(
        (state = {}) => state, 
        applyMiddleware(thunk)
    );

ReactDOM.render(( 
    <Provider store={store}>
      <Router>
        <switch>
            <Route exact path="/" component={App} />
            <Route path="/Loginregister" component={Login} />
        </switch>
      </Router>
    </Provider>  ),
  document.getElementById('root')
);

因为我在'applyMiddleware'中传递'thunk'作为'applyMiddleware(thunk)'然后我在控制台上得到以下错误 -

Uncaught TypeError: Cannot call a class as a function
    at _classCallCheck (index.js:15)
    at ReactThunk (index.js:36)
    at applyMiddleware.js:51
    at createStore (createStore.js:65)
    at Object.<anonymous> (index.js:11)
    at __webpack_require__ (bootstrap b42575b…:555)
    at fn (bootstrap b42575b…:86)
    at Object.<anonymous> (bootstrap b42575b…:578)
    at __webpack_require__ (bootstrap b42575b…:555)
    at bootstrap b42575b…:578

请让我知道我做错了什么。

reactjs redux-thunk
2个回答
14
投票

你正在进口

import thunk from 'react-thunk';

但是thunk来自redux-thunk模块。

所以你应该导入

import thunk from 'redux-thunk';

此外,我认为你的“createStore”调用会出现问题。

createStore采用reducer(或组合reducer)和可能的中间件。

reducer采用状态和动作,并且必须返回商店的新状态。

function reducer(state, action){

  // Switch-Case for action.type
  // Copy the current state and apply changes

  return state;
}

1
投票

那么,从错误中你的问题是显而易见的。您不能将函数作为类发送。在createStore()你的第一个参数是一个函数。它应该是你拥有的减速器。

使用您拥有的Reducer创建一个文件,将其导入索引文件。然后做点什么

const store = createStore(rootReducer, applyMiddleware(thunk))
© www.soinside.com 2019 - 2024. All rights reserved.