@hollanditkzn

Как избавиться от ошибки Uncaught Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWi?

Не пойму почему у меня ошибка
Uncaught Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

Как вообще от нее избавиться?
Просто я внедрил redux-persist
Вот мои весь код
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import  { Provider } from 'react-redux';
import { createStore, combineReducers, compose, applyMiddleware } from 'redux';
import { Route, Switch, Redirect } from 'react-router';
import { BrowserRouter } from 'react-router-dom';
import { PersistGate } from 'redux-persist/lib/integration/react';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import thunk from 'redux-thunk';
import Helmet from './aplication';
import loginReducers from './reducer/loginDucks';
import Auth from "./AuthForm";
import Home from "./Home";

const rootReducer = combineReducers({
    login: loginReducers,
});

const persistConfig = {
    key: 'root',
    storage: storage
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(persistedReducer, composeEnhancers(
    applyMiddleware(thunk)
));

const persisrtor = persistStore(store);

ReactDOM.render(
        <div>
        <Helmet title='Авторизация'/>
        <Provider store={store}>
            <PersistGate loading={null} persistor={persisrtor}>
                <BrowserRouter>
                    <Switch>
                        <Route exact path='/' component={Auth}/>
                        <Route path='/index' component={Home}/>
                    </Switch>
                </BrowserRouter>
            </PersistGate>
        </Provider>
        </div>,
    document.getElementById('content')
);

AuthFrom.js
import React, { Component } from 'react';
import { Redirect } from 'react-router';
import { connect }from 'react-redux';
import TextField from 'material-ui/TextField';
import RaiseButtin from 'material-ui/RaisedButton';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import injectTapEventPlugin from 'react-tap-event-plugin';
import { login } from './reducer/loginDucks';

injectTapEventPlugin();

class UserForm extends Component{
    state = {
        form: {
            login: "",
            password: ""
        }
    };

    handleSubmit = e => {
        e.preventDefault();
        this.props.login(this.state.form);
    };

    handleChange = e => {
        const { name, value } = e.target;

        this.setState( prevState => ({
            form: {
                ...prevState.form,
                [name]: value,
            }
        }));
    };

    render(){
        const { form } = this.state;
        const { isLoading, isError, shouldRedirect, errorMessage } = this.props;
        if (shouldRedirect) return <Redirect to='/index'/>;
        return(
            <div className='authForm'>
                <h1>Авторизация</h1>
                <div className='error'>{isError && errorMessage}</div>
                <form onSubmit={this.handleSubmit}>
                    <MuiThemeProvider>
                        <TextField
                            hintText="Введите логин"
                            name="login"
                            fullWidth={true}
                            value={form.login}
                            required={true}
                            onChange={this.handleChange}
                        />
                    </MuiThemeProvider>
                    <MuiThemeProvider>
                        <TextField
                            hintText="Введите пароль"
                            type="password"
                            name="password"
                            fullWidth={true}
                            value={form.password}
                            required={true}
                            onChange={this.handleChange}
                        />
                    </MuiThemeProvider>
                    <MuiThemeProvider>
                        <RaiseButtin label="Войти" fullWidth={true} className="authForm-button"> <input type="submit" className="authForm-input" /> </RaiseButtin>
                    </MuiThemeProvider>
                </form>
            </div>
        );
    }
}

const mapStateToProps = state => ({
    isLoading: state.login.isLoading,
    isError: state.login.isError,
    shouldRedirect: state.login.shouldRedirect,
    errorMessage: state.login.errorMessage,
});

const mapDispatchToProps = {
    login,
};

export default connect(mapStateToProps, mapDispatchToProps)(UserForm)

И вытащу locginDucks.js потому что файл AuthForm.js не стоит
import axios from 'axios';

const LOGIN_REQUEST = 'LOGIN_REQUEST',
    LOGIN_SUCCESS = 'LOGIN_SUCCESS',
    LOGIN_ERROR = 'LOGIN_ERROR';

const loginSuccess = data => ({
    type: LOGIN_SUCCESS,
    payload: {id: data.id, login: data.login, name: data.name}
});

const loginError = data => ({
    type: LOGIN_ERROR,
    payload: data
});

export const login = form => async dispatch => {
    try {
        const res = await axios.post('/api/user', form);
        if (!res.data || res.data === false) {
            dispatch(loginError('Неправильный логин или пароль'));
        } else {
            dispatch(loginSuccess(res.data));
        }
    } catch (e) {
        dispatch(loginError(e.response.data));
    }
};

const initialState = {
    isLoading: false,
    isError: false,
    shouldRedirect: false,
    errorMessage: '',
    user: 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,
                user: payload,
                isLoading: false,
                shouldRedirect: true,
                auth: true,
            };
        case LOGIN_ERROR:
            return {
                ...state,
                errorMessage: payload,
                isLoading: false,
                isError: true,
            };
        default:
            return state;
    }
}

Это при авторизации
  • Вопрос задан
  • 924 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы