使用 React 18 StrictMode 对 useEffect 进行不需要的 thunk 双重调度

6ra*_*her 8 reactjs redux redux-thunk react-redux react-hooks

我试图在页面的第一次渲染和按钮单击时调度一个重击。这是它的示例代码:

export default function App() {
  const [loading, setLoading] = useState(false);
  const [finished, setFinished] = useState(false);
  const count = useSelector(countSelector);
  const dispatch = useDispatch();

  const appendCounter = useCallback(() => {
    if (!loading) {
      setLoading(true);
      setFinished(false);

      dispatch(thunk()).finally(() => {
        setLoading(false);
        setFinished(true);
      });
    }
  }, [loading, dispatch]);

  useEffect(() => {
    if (!loading && !finished) {
      appendCounter();
    }
  }, [appendCounter, loading, finished]);

  return (
    <div className="App">
      {!loading && finished ? (
        <>
          <h2>{count}</h2>
          <button onClick={appendCounter}>Append</button>
        </>
      ) : (
        <h2>loading</h2>
      )}
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>
);
Run Code Online (Sandbox Code Playgroud)

我正在使用带有 StrictMode 的 React 18。在 React 17 上,一切正常,但在 18 上,我在页面渲染上收到两个调度的 thunk。我认为这是由于React 18 中的 StrictMode 更改所致。如何修复代码以防止双重调度?该代码也可以在CodeSandbox上找到。