redux RTK提取查询错误是多次显示吐司

rta7y2nd  于 2023-05-18  发布在  其他
关注(0)|答案(1)|浏览(127)

我正在使用RTK查询获取数据,但当发生错误时,我使用react-toastify库创建了一个吐司,该库多次显示toast消息如何防止这种情况?当我consollog时,我看到“if”条件的那部分呈现了多次。

import FoodBox from "../components/FoodBox";

import styled from "styled-components";
import { useFetchFoodsQuery } from "../store";
import { useSelector } from "react-redux";
import Skeleton from "./Skeleton";
import { toast } from "react-toastify";

const Foods = styled.div`
  overflow-y: auto;
  overflow-x: hidden;
  height: 370px;
  padding: 0 30px;
`;

function FoodList({ shopId }) {
  let { data: foods, error, isFetching } = useFetchFoodsQuery(shopId);
  const user = useSelector((state) => state.user.currentUser);
  let content;
  if (isFetching) {
    content = (
      <Foods>
        <Skeleton w="22.5rem" h="3.5rem" times={5} />
      </Foods>
    );
  } else if (error) {
    toast('Error');
    return <div>Error in loading food</div>;
  } else {
    if (!user) {
      foods = foods?.filter((food) => food.isVisible);
    }
    content = (
      <Foods>
        {foods?.map((food) => (
          <FoodBox key={food?._id} food={food} />
        ))}
      </Foods>
    );
  }

  return content;
}

export default FoodList;

输出:x1c 0d1x

cbjzeqam

cbjzeqam1#

代码调用toast作为React组件生命周期之外的无意副作用。React组件的render方法(* 是的,整个React函数组件体都是“render方法”)被认为是一个纯函数,没有副作用。“双重渲染”最有可能发生在将应用渲染到React.StrictMode组件时,它故意双重调用特定的生命周期方法,并双重挂载组件作为调试方法,以帮助您找到代码中的问题,***例如**意外的副作用。
参见:

  • 检测意外副作用
  • 确保可重用状态
  • 修复开发中双重渲染发现的bug
  • 修复在开发中重新运行特效发现的bug

从预期的生命周期方法中调度吐司,例如useEffect钩子useEffect是“每个组件渲染***到DOM***的一个副作用”。
示例:

function FoodList({ shopId }) {
  const { data: foods, error, isFetching } = useFetchFoodsQuery(shopId);
  const user = useSelector((state) => state.user.currentUser);

  // Issue intentional side effect
  React.useEffect(() => {
    if (error) {
      toast('Error');
    }
  }, [error]);

  if (isFetching) {
    return (
      <Foods>
        <Skeleton w="22.5rem" h="3.5rem" times={5} />
      </Foods>
    );
  } else if (error) {
    return <div>Error in loading food</div>;
  } else {
    return (
      <Foods>
        {foods?.filter((food) => !!user || food.isVisible
          .map((food) => <FoodBox key={food?._id} food={food} />)
        }
      </Foods>
    );
  }
}

相关问题