user.redux.js代码
注意axios是异步的,要传回调函数dispatch动作
import axios from 'axios';
const REGISTER_SUCCESS = 'REGISTER_SUCCESS'; //actionType
const ERROR_MESSAGE = 'ERROR_MESSAGE'; //actionType
const initState = {
isAuth:false,
msg:'',
username:'',
upwd:'',
type:'',
}
export const user = (state=initState,action)=>{ //reducer
switch(action.type){
case REGISTER_SUCCESS:
return { ...state, ...action.data, msg:'', isAuth:true }
case ERROR_MESSAGE:
return { ...state , msg:action.msg , isAuth:false }
default
return state ;
}
}
function RegisterSucc(data){ //actionCreater
return { data,type:REGISTER_SUCCESS } ;
}
function ErrorMsg(msg){ //actionCreater
return { msg,type:ERROR_MESSAGE } ;
}
export const register = ({username,upwd,repeatUpwd,type})=>{ //处理注册表单
if(!username||!upwd||!repeatUpwd){
return ErrorMsg('用户名密码不能为空');
}
if(upwd!==repeatUpwd){
return ErrorMsg('两次输入密码不正确');
}
return (dispatch)=>{
axios.post('/user/register',{ username,upwd,repeatUpwd,type })
.then(res=>{
if(res.status==200&&res.data.code===0){
dispatch(RegisterSucc(res.data));
}else{
dispatch(ErrorMsg(res.data.msg))
}
})
}
}
把reducer user 暴露出去,用combineReducers打包一下。
import { combineReducers } from 'redux';
import { user } from '../redux/user.redux.js'
export default combineReducers({ user });
这样就能生成user register 相关的store了。