Redux错误操作必须是普通对象。使用自定义中间件进行异步操作

时间:2019-08-21 06:42:02

标签: javascript reactjs redux react-redux redux-thunk

我是Redux的新手,在执行错误操作时遇到了错误

“动作必须是普通对象。对异步动作使用自定义中间件。”,我已经检查了流程,但看不到任何问题,这是下面的代码”

我的JS容器文件:

import React from 'react'
import {Redirect} from 'react-router-dom'
import * as actions from './../store/actions/index'
import { connect } from 'react-redux'

class home extends React.Component{

constructor(props){
    super(props);
    this.state={
        isClk:false
    }
}


performLogout = (evt)=> {
    evt.preventDefault();
    this.props.onLogout();
    this.setState({isClk: true})
};

render(){

    let redirect=null;

    if (this.state.isClk){
        redirect=<Redirect to="/login"/>
    }
    return(

        <div>
            {redirect}
            <h1>In Home</h1>
            <button onClick={this.performLogout}>Logout</button>
        </div>
    )
}

}

  const mapDispatchToProps = dispatch =>{
     return {
      onLogout: () => dispatch(actions.logout())
    }
  };

 export default connect(null,mapDispatchToProps)(home)

Index.js:

   export {
auth,
logout
} from './auth'

Actions(auth.js):

export const logout =()=>{
 return(
    actionTypes.AUTH_LOGOUT
 )
};

减速器:

  const authLogout=(state,action)=>{
     return updateObject(state,{
         token:null,
         loading:false,
         error:null
    })
   };

 const reducer=(state=initialState,action)=>{

 switch(action.type){
    case actionTypes.AUTH_FAIL: return authFail(state,action);
    case actionTypes.AUTH_LOGOUT: return authLogout(state,action);
    default:
        return state
  }

 };

商店:

       import {Provider} from 'react-redux'
       import { createStore, applyMiddleware, compose, combineReducers } from 'redux'
       import {BrowserRouter} from "react-router-dom";
       import authReducer from './Containers/store/reducers/auth'
       import thunk from 'redux-thunk';

       const composeEnhancers = compose;

       const RootReducer=combineReducers({
              auth:authReducer
       });

       const store=createStore(RootReducer,composeEnhancers(applyMiddleware(thunk)));

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

ReactDOM.render(app,document.getElementById('root'));

我想在用户单击注销按钮时执行注销操作,我可以找到问题所在,我的商店是否已正确初始化或是否有任何问题?或其他任何人在派遣时,请提供指导?

2 个答案:

答案 0 :(得分:1)

您的动作创建者应该返回具有类型的对象,当前您仅返回字符串常量。

// Actions(auth.js):

export const logout =()=>{
 return {
    type: actionTypes.AUTH_LOGOUT,
 };
};

答案 1 :(得分:1)

Redux中的操作必须是普通对象,因此您需要添加以下对象

export const logout = () => ({
    type: actionTypes.AUTH_LOGOUT
});