axios GET请求持续运行

时间:2020-05-24 17:23:01

标签: javascript node.js reactjs express

我在我的React应用程序上工作,发现一个错误。当我在控制台上记录以下代码(即来自Express后端的GET请求)时,控制台日志将不停止运行。

api-helper.js(REACT)

export const getAllPages = async () => {
  getToken();
  const resp = await api.get(`pages/`);
  console.log('><><><><><><><>< return getAllPages response ><><><><><><><><',resp) // 
  const parsedResponse = resp.data.map((page) => ({
    ...page,
    siteName: page.siteUniqueName?.split("-")[1],
  }));
  return parsedResponse;
};

pageRouter.js(表达)

pageRouter.get("/", restrict, async (req, res, next) => {
  try {
    const { user } = req;
    const pages = await Page.findAll({
      where: {
        userId: user.id
      },
      include: [
        { model: Site },
        { model: VisitRecord },
        { model: Lead }
      ]
    });
    res.json(pages);
  } catch (e) {
    next(e);
  }
});

如果它在实时数据库上进行调用,显然对生产不利。我该如何阻止它在后台不断运行?

更新

这是仪表板上的代码,该代码调用呈现所有页面的API:

Dashboard.jsx

  useEffect(() => {
    props.getAllPages();
  }, []);

App.js

  getAllUserPages = async () => {
    // console.log('called here1')
    const pages = await getAllPages();
    if (pages) {
      this.setState({
        sites: pages,
      });
    }
  };

  async componentDidMount() {
    // console.log('called________')
    const currentUser = await getCurrentUser();
    if (currentUser) {
      const preservedSites = await getAllPages();
      this.setState({
        currentUser,
        preservedSites: preservedSites.map((site) => site.siteName),
      });
    } else {
      if (
        !(
          this.props.history.location.pathname.startsWith("/reset/") ||
          this.props.history.location.pathname === "/" ||
          matchPath(this.props.history.location.pathname, {
            path: "/:userId/:siteName",
            exact: false,
            strict: false,
          })
        )
      ) {
        this.props.history.push("/auth");
      }
    }
    const pages = await getAllPages();
    if (pages) {
      this.setState({
        sites: pages,
      });
    }
    const resp = await api.get("/users");
    const users = resp.data;
    this.setState({
      users: users,
    });
  }

0 个答案:

没有答案