英文:
React Router cancel loader
问题
我在加载程序中抛出错误时,当fetch
的response.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的任何定义值。我认为重要的细节是你应该返回某些内容,而不是undefined
。null
似乎可以正常工作,并且不会引发任何额外的错误。
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 {};
}
It's really up to your app's, or code's, specific use case what it returns and how the UI handles it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论