我正在尝试添加redux-thunk中间件以在我的应用程序中添加注册和登录功能。但是该代码似乎不适用于注册。它给出了以下错误-
动作必须是普通对象。使用自定义中间件执行异步操作。
代码如下
Index.js -导入并使用thunk
import {createStore, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
const store = createStore(authReducer,applyMiddleware(
thunk,
loggerMiddleware
),window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root'));
actions / authActions.js -创建注册函数以分派动作
export function register(){
return (dispatch)=>{
dispatch({type:'auth_user'})
}
}
components / Register.js -使用上述Redux寄存器功能的组件
import * as actions from '../actions/authActions';
class RegisterForm extends React.Component{
handleRegister = (e)=>{
e.preventDefault();
console.log("inside handle register");
console.log(this.props);
this.props.register();
}
}
var Register = connect(mapStateToProps,actions)(RegisterForm);
authReducer.js
import {AUTH_ERROR,UNAUTH_USER,FETCH_MESSAGE, AUTH_USER} from '../actions/types';
const initialState = {
loggedIn:false,
errorMessage:''
}
const authReducer = (state=initialState,action)=>{
console.log("action is")
console.log(action);
switch(action.type){
case AUTH_USER:
{
console.log("Reached in reducer");
return {...state,loggedIn:true}}
case UNAUTH_USER:
return {...state, loggedIn:false}
default:
return state;
}
}
export default authReducer;
/action/types.js
export const AUTH_USER = 'auth_user'
export const UNAUTH_USER = 'unauth_user'
export const AUTH_ERROR = 'auth_error'
export const FETCH_MESSAGE = 'fetch_message'
答案 0 :(得分:1)
您的商店设置似乎不正确。将您的商店写为:
secondReducer
答案 1 :(得分:0)
您可以在操作中尝试以下代码段。
export function register=()=>{
return {
type:'auth_user'
}
}