使用React的useState处理错误

时间:2019-03-07 20:19:28

标签: javascript reactjs react-hooks

如果我有一个类似于以下内容的组件:

import React, { useState } from "react";
import ReactDOM from "react-dom";

function calculateNewValueAndMaybeError(test) {
  try {
    // do something with test that might error
    // const newTest = functionThatMightError(...)
    // if it doesn't error, return { value: newTest, error: '' }
  } catch (err) {
    // is it correct to now return this in case of error?
    // return { value: test.value, error: 'Something went wrong' }
  }
}

function App() {
  const [test, setTest] = useState({ value: "", error: "" });
  return (
    <div>
      <p>Test: {test.value}</p>
      <p>Error: {test.error}</p>
      <button onClick={() => setTest(calculateNewValueAndMaybeError(test))}>
        Click me
      </button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

我有一个按钮应该改变变量test的状态,有没有一种方法可以处理错误而不必始终在内部传递带有值和错误的对象?

否则,这有时不会导致必要的代码,如下所示:

onChange={() => setTest({ value: e.target.value, error: test.error })}

要更新test.value的值但保留test.error的值的地方。

我觉得我很想念一些东西。

谢谢!

1 个答案:

答案 0 :(得分:2)

需要合并两个州,这表明它们应该作为不同州处理:

function App() {
  function calculateNewValueAndMaybeError(test) {
    try {
      ...
      setValue(...);
      setError(null);
    } catch (err) {
      setError('Something went wrong');
    }
  }

  const [error, setError] = useState(null);
  const [value, setValue] = useState('');
  return (
    <div>
      <p>Test: {value}</p>
      <p>Error: {error}</p>
      <button onClick={() => setTest(calculateNewValueAndMaybeError(test))}>
        Click me
      </button>
    </div>
  );
}

或者可以使用自定义状态挂钩来合并error字段:

const useErrorState = initialState => {
  const [state, setState] = useState({ ...initialState, error: null });
  const setErrorState = useCallback(stateUpdater => {
    if (typeof stateUpdater === 'function') {
      setState(state => {
        try {
          return {error: null, ...stateUpdater(state) };
        } catch (error) {
          return {...state, error };
        }
      });
    } else {
      setState({error: null, ...stateUpdater });
    }
  }, []);

  return [state, setErrorState];
}

另一种可能性是将错误处理转移到父组件(可能是高阶组件)并在那里捕获错误。