反应-错误:超过最大更新深度-useReducer

时间:2020-08-29 06:02:14

标签: reactjs typescript

我遇到错误:

react-dom.development.js:23093未捕获的错误:超出最大更新深度。当组件重复调用componentWillUpdate或componentDidUpdate内部的setState时,可能会发生这种情况。 React限制了嵌套更新的数量,以防止无限循环。

我知道问题可能是由于我正在通过useEffect钩子调用的checkValidations函数中调用通过useReducer修改状态的checkError和validationPassed函数而导致的,但我不知道解决方法

代码为:

interface ValidationField {
  errorMessage?: string;
  focused: boolean;
  hasError: boolean;
}

interface ClientEditorState {
  client: Client;
  validations: { [key in keyof Client]: ValidationField };
}

enum clientEditorActions {
  UPDATE_ENTITY = 'CLIENT_EDITOR/UPDATE_ENTITY',
  UPDATE_FOCUSED = 'CLIENT_EDITOR/UPDATE_FOCUSED',
  VALIDATION_ERROR = 'CLIENT_EDITOR/VALIDATION_ERROR',
  VALIDATION_PASSED = 'CLIENT_EDITOR/VALIDATION_PASSED',
}

interface UpdateEntityAction extends Action<typeof clientEditorActions.UPDATE_ENTITY> {
  name: string;
  value: string | boolean;
}
interface UpdateFocusedAction extends Action<typeof clientEditorActions.UPDATE_FOCUSED> {
  name: string;
}
interface ValidationErrorAction extends Action<typeof clientEditorActions.VALIDATION_ERROR> {
  message: string;
  name: string;
}
interface ValidationPassedAction extends Action<typeof clientEditorActions.VALIDATION_PASSED> {
  name: string;
}

type ClientEditorActions = UpdateEntityAction | UpdateFocusedAction | ValidationErrorAction | ValidationPassedAction;

const clientReducer: Reducer<ClientEditorState, ClientEditorActions> = (prevState, action) => {
  switch (action.type) {
    case clientEditorActions.UPDATE_ENTITY:
      const clientUpdated = _cloneDeep(prevState || ({} as Client));
      _set(clientUpdated, `client.${action.name}`, action.value);
      return clientUpdated;
    case clientEditorActions.UPDATE_FOCUSED:
      const validationField = _cloneDeep(prevState);
      _set(validationField, `validations.${action.name}.focused`, true);
      return validationField;
    case clientEditorActions.VALIDATION_ERROR:
      const errorField = _cloneDeep(prevState);
      _set(errorField, `validations.${action.name}.hasError`, true);
      _set(errorField, `validations.${action.name}.errorMessage`, action.message);
      return errorField;
    case clientEditorActions.VALIDATION_PASSED:
      const passed = _cloneDeep(prevState);
      _set(passed, `validations.${action.name}.hasError`, false);
      _set(passed, `validations.${action.name}.errorMessage`, undefined);
      return passed;
    default:
      return prevState;
  }
};

...

const getInitialState = (): ClientEditorState => ({
    client: entity as Client,
    validations: {
      firstName: {
        focused: false,
        hasError: false,
      },
     
    },
  });
  const [state, clientDispatch] = useReducer(clientReducer, getInitialState());

  const checkError = useCallback((name: string, message: string) => {
    clientDispatch({
      type: clientEditorActions.VALIDATION_ERROR,
      name,
      message,
    });
  }, []);

  const validationPassed = useCallback((name: string) => {
    clientDispatch({
      type: clientEditorActions.VALIDATION_PASSED,
      name,
    });
  }, []);

const checkValidations = useCallback(
    (c: Client) => {
      let validation = false;

      const { firstName } = state.validations;

      if (!c.firstName && firstName.focused) {
        validation = false;
        checkError('firstName', f('client.requiredFieldClient'));
      } else {
        validation = true;
        validationPassed('firstName');
      }

    
    },
    [checkError, f, state.validations, validationPassed],
  );

  const [clientUpdateHandler] = useDebouncedCallback((clientUpdated: Client) => {
    dispatch(updateEntityEditor(clientUpdated));
  }, 800);

  useEffect(() => {
    if (!_isEqual(state.client, entity)) {
      clientUpdateHandler(state.client as Client);
    }
    const { firstName } = state.validations;

    if (firstName.focused) checkValidations(state.client);
  }, [checkValidations, clientUpdateHandler, entity, state.client, state.validations]);

1 个答案:

答案 0 :(得分:0)

我知道问题可能是由于我在通过useEffect钩子调用的checkValidations函数中调用通过useReducer修改状态的checkError和validationPassed函数导致的。

是的,是的。尝试减少useEffect和useCallback中关联函数的依赖性。这些更改中的任何一项都会导致useEffect重新运行。

回到问题,您的useEffect当前取决于state.validations。因此,每当state.validations更改时,useEffect都会重新运行。考虑做

const { firstName } = state.validations;

useEffect和checkValidations回调之外。这将阻止它在每次状态变化时重新运行。