Примерно так это можно сделать:
Ваш компонент:
import { login } from './loginDucks';
class UserForm extends Component {
...
handleSubmit = e => {
this.props.login(this.state.form);
}
...
render() {
const { isLoading, isError, shouldRedirect } = this.props;
if (shouldRedirect) <Redirect to="/index" >;
return (
...
);
}
}
const mapStateToProps = state => ({
isLoading: state.login.isLoading,
isError: state.login.isError,
shouldRedirect: state.login.shouldRedirect,
});
const mapDispatchToProps = {
login,
};
export default connect(mapStateToProps, mapDispatchToProps)(UserForm);
loginDucks.jsconst LOGIN_REQUEST = 'LOGIN_REQUEST';
const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
const LOGIN_ERROR = 'LOGIN_ERROR';
const loginSuccess = data => ({
type: LOGIN_SUCCESS,
payload: data,
});
const loginError = data => ({
type: LOGIN_ERROR,
});
export const login = form => async dispatch => {
try {
const res = await axios.post('/api/user', form);
if (!res.data) dispatch(loginError());
dispatch(loginSuccess());
} catch e {
dspatch(loginError());
}
}
const initialState = {
isLoading: false,
isError: false,
shouldRedirect: false,
};
export default (state = initialState, action) => {
const { type, payload } = action;
switch(type) {
case LOGIN_REQUEST:
return {
...state,
isLoading: true,
isError: false,
};
case LOGIN_SUCCESS:
return {
...state,
isLoading: false,
shouldRedirect: false,
};
case LOGIN_ERROR:
return {
...state,
isLoading: false,
isError: true,
};
default:
return state;
}
};
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, combineReducers, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { Route, Switch } from 'react-router';
import { BrowserRouter } from 'react-router-dom';
import Auth from './component/AuthForm';
import Helmet from './aplication';
import loginReducer from './loginDucks';
function user(state = {}, action){
if(action.type === 'ADD_USER'){
return [
...state,
action.user
];
}
return state;
}
const rootReducer = combineReducers({
login: loginReducer,
user,
});
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(rootReducer, composeEnhancers(
applyMiddleware(thunk),
));
ReactDOM.render(
<div>
...
</div>,
document.getElementById('content')