这是用户中间件...
import axios from 'axios';
import { useDispatch } from 'react-redux';
import {
SUBMIT_NEW_USER,
SUBMIT_LOGIN,
saveAuthData,
} from 'src/actions/form';
const userMiddleware = (store) => (next) => (action) => {
switch (action.type) {
case SUBMIT_NEW_USER:
axios.post(
'xxxxxx/api/users',
{
firstname: store.getState().userNameSubscribe,
lastname: store.getState().userLastNameSubscribe,
phoneNumber: store.getState().userPhoneSubscribe,
email: store.getState().userMailSubscribe,
personalAddress: store.getState().userAdressSubscribe,
password: store.getState().userPasswordSubscribe,
},
)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
break;
case SUBMIT_LOGIN:
axios.post(
'xxxxxxx/api/login_check',
{
username: store.getState().logInEmail,
password: store.getState().logInPassword,
},
)
.then(function (response) {
console.log(response);
store.dispatch(saveAuthData(response.data.token));
})
.catch(function (error) {
console.log(error);
});
break;
}
next(action);
};
export default userMiddleware;
下面是userReducer:
import { HANDLE_CHANGE, SAVE_AUTH_DATA } from '../actions/form';
const initialState = {
userNameSubscribe: '',
userLastNameSubscribe: '',
userPhoneSubscribe: '',
userMailSubscribe: '',
userAdressSubscribe: '',
userPasswordSubscribe: '',
logInEmail: '',
logInPassword: '',
token: '',
loged: false,
};
const userReducer = (state = initialState, action = {}) => {
switch (action.type) {
case TOGGLE_FORM:
return {
...state,
openLogin: !state.openLogin,
};
case HANDLE_CHANGE:
return {
...state,
[action.name]: action.value,
};
case SAVE_AUTH_DATA:
return {
...state,
token: action.token,
loged: true,
};
default:
return state;
}
};
export default userReducer;
断根剂:
import { combineReducers } from 'redux';
import spaceReducer from './spaceReducer';
import userReducer from './userReducer';
const rootReducer = combineReducers({
space: spaceReducer,
user: userReducer,
});
export default rootReducer;
最后是商店:
import { legacy_createStore as createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import reducer from 'src/reducers';
import userMiddleware from '../middleware/userMiddleware';
import spaceMiddleware from '../middleware/spaceMiddleware';
const middlewares = applyMiddleware(
userMiddleware,
spaceMiddleware,
);
const enhancer = composeWithDevTools(middlewares);
const store = createStore(reducer, enhancer);
export default store;
在userMiddleware中,如果我输入用户名:name@email.com和密码:实际密码,而不是使用store.getState().logInEmail和store.getState().logInPassword:name@email.com和therealpassword位于有效负载中,而我使用getState()时并非如此....
谁能告诉我问题出在哪里?
1条答案
按热度按时间ozxc1zmp1#
有了两个reducer,我必须在userMiddleware中精确它,所以store.getState().user而不是仅仅store.getState()完成了这项工作。