redux 如何修复在模拟调度时有条件调用useDispatch REACT挂接

5jvtdoz2  于 2022-11-12  发布在  React
关注(0)|答案(1)|浏览(118)

错误消息:React Hook“useDispatch”是有条件调用的。在每个组件呈现中,必须以完全相同的顺序调用React Hook
几天来我一直在想如何修复这个问题,但是没有任何效果。当我不模拟任何东西的时候,这个组件可以工作,但是当我模拟调度的时候,它就给我这个错误。
以下是我的组件:

import { Stage } from "../Stage/Stage";
import { useDispatch, useSelector } from "react-redux";
import { useEffect } from "react";
import { retrieveStageList } from "../../modules/reducer";
import { Process } from "../Process/Process";

export function RenderProcess({
  _useSelector = useSelector,
  _useDispatch = useDispatch(), //this is where it breaks
  _Process = Process,
}) {
  const dispatch = _useDispatch();
  const process = _useSelector((state) => state.renderProcess);
  const stageList = _useSelector((state) => state.stageList);
  useEffect(() => {
    if (process.processId !== null)
      dispatch(retrieveStageList(process.processId));
  }, []);

  return (
    <>
      <_Process process={process} />
      {stageList?.map((stageInputs, processId) => {
        return (
          <div key={processId}>
            <Stage stage={stageInputs} />
          </div>
        );
      })}
    </>
  );
}

下面是我对这个组件的测试:

import { render } from "@testing-library/react";
import { RenderProcess } from "./RenderProcess";

test("should call dispatch once.", () => {
  const _useSelector = (fn) =>
    fn({
      stageList: [],
      renderProcess: { processId: "309624b6-9c96-4ba7-8f7e-78831614f685" },
    });

  const dispatch = jest.fn();
  render(
    <RenderProcess
      _useSelector={_useSelector}
      _useDispatch={() => dispatch}
      _Process={() => {}}
    />
  );
  expect(dispatch).toHaveBeenCalledTimes(1);
});

如果能帮上忙就太好了。

h43kikqp

h43kikqp1#

在RenderProcess中传递的属性中找到了修复-在此

  • 生产线:_useDispatch = useDispatch()
  • 它应该是:_useDispatch = useDispatch

相关问题