30秒学会 React 片段 · 2023年11月30日

30秒学会 React 片段 – React useError hook

Creates an error dispatcher.

  • Use the useState() hook to create a state variable that holds the error.
  • Use the useEffect() hook to throw the error whenever it’s truthy.
  • Use the useCallback() hook to update the state and return the cached function.

代码实现

const useError = err => {
  const [error, setError] = React.useState(err);

  React.useEffect(() => {
    if (error) throw error;
  }, [error]);

  const dispatchError = React.useCallback(err => {
    setError(err);
  }, []);

  return dispatchError;
};

使用样例

const ErrorButton = () => {
  const dispatchError = useError();

  const clickHandler = () => {
    dispatchError(new Error('Error!'));
  };

  return <button onClick={clickHandler}>Throw error</button>;
};

ReactDOM.createRoot(document.getElementById('root')).render(
  <ErrorButton />
);

翻译自:https://www.30secondsofcode.org/react/s/use-error