React Router取消加载器

huangapple go评论49阅读模式
英文:

React Router cancel loader

问题

我在加载程序中抛出错误时,当fetchresponse.status.ok为false时,会加载错误组件。

但是我的服务器有时会返回429状态码(请求过多),在这种情况下,我不想加载错误组件,而是什么都不做,或者可能显示一些消息,但肯定不重新加载已加载的组件,也不重定向等。
这该怎么实现?

英文:

I'm throwing an error in my loaders when response.status.ok of fetch is false. Error component is then loaded.

But my server sometimes returns 429 status code (too many requests) upon which I don't want to load an error component but instead simply do nothing, or maybe display some message but certainly without reloading the already loaded component, or redirecting, etc.
How can that be implemented?

https://codesandbox.io/s/hungry-hooks-yuucsp?file=/src/App.js

答案1

得分: 1

你可以针对状态码为429的情况进行特殊处理,并返回UI的任何定义值。我认为重要的细节是你应该返回某些内容,而不是undefinednull 似乎可以正常工作,并且不会引发任何额外的错误。

function loader() {
  let response = imitateFetch();
  console.log(response);

  if (response.status === 429) {
    console.log(429);
    return null; // <-- 返回 null
  }

  if (!response.ok) {
    throw "loader error";
  }
  return {};
}

但你可以返回任何你喜欢的东西,例如,将响应状态更改为200。

function loader() {
  let response = imitateFetch();
  console.log(response);

  if (response.status === 429) {
    console.log(429);
    response.status = 200;
    response.ok = true;
    return response;
  }

  if (!response.ok) {
    throw "loader error";
  }
  return {};
}

这真的取决于你的应用程序或代码的具体用例,以及它返回什么以及UI如何处理它。

英文:

You can check the response status code specifically for a 429 status and return any defined value back to the UI. I think the important detail here that you should return something instead of undefined. null appears to work and not throw any extraneous errors

function loader() {
  let response = imitateFetch();
  console.log(response);

  if (response.status === 429) {
    console.log(429);
    return null; // <-- return null
  }

  if (!response.ok) {
    throw "loader error";
  }
  return {};
}

but you can return anything you like, for example, change the response status to 200.

function loader() {
  let response = imitateFetch();
  console.log(response);

  if (response.status === 429) {
    console.log(429);
    response.status = 200;
    response.ok = true;
    return response;
  }

  if (!response.ok) {
    throw "loader error";
  }
  return {};
}

React Router取消加载器

It's really up to your app's, or code's, specific use case what it returns and how the UI handles it.

huangapple
  • 本文由 发表于 2023年6月2日 00:00:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76383757.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定