【问题标题】:How to cancel previous onClick handler that has two dispatch functions with useEffect()?如何使用 useEffect() 取消以前具有两个调度函数的 onClick 处理程序?
【发布时间】:2022-08-19 06:56:15
【问题描述】:

我看到了这个https://redux-toolkit.js.org/api/createAsyncThunk#canceling-while-running 但我在onClick 处理程序中有两个调度函数。 如何将它们放入useEffect()?

我想实现当用户快速点击另一个项目时,之前的fetchFileContentsHandler 将被取消,并始终返回最新调用的结果。

我试图将fetchFileContentsHandler 包裹在useCallback() 中, 并将fetchFileContentsHandler 放入useEffect() 并进行清理返回。 但它导致了奇怪的行为。

  const fetchFileContentsHandler = () => {
    dispatch(fetchFileContents(props.params));
    dispatch(
      changeSelectedFile({ selectedFile: props.params, selected: true })
    );
  };

  return (
    <NavLink to=\"#\" key={fileName}>
      <ListItemButton
        selected={props.selected}
        onClick={fetchFileContentsHandler}
      >
        <ListItemText
          primary={fileName}
        />
      </ListItemButton>
    </NavLink>
  );
};

export default Items;

[更新] 我尝试将fetchFileContents 更改为createAsyncThunk 并添加建议的useRef() 和.abort(),但没有成功。 如果第一个 fetchFileContents 花费的时间比第二个 fetchFileContents 长,它仍然会更新 htmlReport 或 textReport 值,我会使用这个值并在另一个组件中显示内容。

切片.js

export const fetchFileContents = createAsyncThunk(
  \"ui/getFileContents\",
  async (fileName) => {
    const fileContentsResponse = await fetch(...);
    const response = await fileContentsResponse.json();

    return {
      fileType: fileName.includes(\"html\") ? \"text\" : \"html\",
      contents: data,
    };
  }
);
const Slice = createSlice({
  name: \"somename\",
  initialState: {
    htmlReport: null,
    textReport: null,
  },
  reducers: {
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchFileContents.fulfilled, (state, action) => {
        if (action.payload.fileType === \"textg\") {
          state.textReport = action.payload.contents;
          state.htmlReport = null;
        } else if (action.payload.fileType === \"html\") {
          state.textReport = null;
          state.htmlReport = action.payload.contents;
        }
      })
  },
});

组件.js

const fetchFileContentsPromise = useRef();

  const fetchFileContentsHandler = () => {
    fetchFileContentsPromise.current?.abort();

    fetchFileContentsPromise.current = dispatch(
      fetchFileContents({ fileName: props.params })
    );
    dispatch(
      changeSelectedFile({ selectedFile: props.params, selected: true })
    );
  };

    标签: reactjs redux-toolkit


    【解决方案1】:

    你很接近!

    如果您在找到的the documentation 中向下滚动一点,您会看到它说dispatch(asyncThunk) 将返回一个带有abort 方法的承诺。

    在您的用例中,我们只希望在单击按钮时取消先前的请求。 useEffect 可以工作,但我们必须创建一些额外的状态才能将其放入依赖项数组中,这有点奇怪。

    另一种可能的选择是使用useRef 来存储这些承诺,这样我们就不必处​​理useEffect。我不确定这两个操作是否都是异步 thunk,如果是,您可以尝试:

    const fetchFileContentsPromise = useRef()
    const changeSelectedFilePromise = useRef()
    
    const fetchFileContentsHandler = () => {
      // Cancel previous requests
      fetchFileContentsPromise.current?.abort();
      changeSelectedFilePromise.current?.abort();
    
      // Dispatch actions and send new requests
      fetchFileContentsPromise.current = dispatch(fetchFileContents(props.params));
      changeSelectedFilePromise.current = dispatch(
        changeSelectedFile({ selectedFile: props.params, selected: true })
      );
    }
    

    如果changeSelectedFile 不是createAsyncThunk 创建的动作,那么实际上不可能停止它,因为它是同步的。

    在这种情况下,我建议您在满足fetchFileContents 时将changeSelectedFile 中的逻辑移动到extra reducer,以便我们仅在完成fetchFileContents 时执行这些代码。

    【讨论】:

    • 该解决方案不起作用,请参阅我的帖子中的[更新]。
    猜你喜欢
    • 1970-01-01
    • 2021-01-10
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多