javascript - 如果 React Js 中的 API 调用失败,如何重定向?
问题描述
我正在尝试在我的 react js 应用程序中实现重定向,因此如果 API 调用返回 200 以外的状态,我可以将用户重定向到相应的页面。问题是重定向不起作用。到目前为止我的代码:
function catchErr(res) {
try {
if (res.status === 200) {
return res.json();
} else if (res.status === 404) {
<Redirect to="/404" // doesn't redirect to this route
console.log("404") // prints 404
throw Error(res.status);
}
else {
if (res.ok) {
return res.data;
}
}
} catch (err) {
console.log(err);
}
}
export async function getData() {
let getParams = {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
};
const data = await fetch(url, obj)
.then((res) => catchErr(res))
.then((res) => {
return res.data;
});
return data;
}
我的 api 调用是单独文件中的一个函数,它不是反应功能组件,所以我不能使用 useState 挂钩来存储状态或在 getData() 函数中使用 useHistory(history.push)。目前 api 调用效果很好,如果 res.status === 404,catchErr() console.loges 404 但不会根据需要重定向到“/404”。我不知道为什么在这种情况下重定向不起作用,请帮忙。
解决方案
你不能在函数中间调用 JSX。您需要重构代码以处理 React 组件中的故障,并设置一些状态以有条件地将Redirect
组件渲染到 DOM 或访问history
对象以执行命令式重定向,即history.replace
.
这是一个使用history.replace
.
import { useHistory } from 'react-router-dom';
const MyComponent = () => {
const history = useHistory();
...
useEffect(() => {
const fetchData = async () => {
// set any loading state
try {
const response = await fetch(url, options);
// process response, throw error if STATUS 404
} catch(error) {
// handle any error responses and redirect
history.replace("/404");
} finally {
// clear any loading state
}
}
fetchData();
}, []);
...
return (
<div>My JSX</div>
)
};
推荐阅读
- python - 在python中将多值字典转换为数据框
- node.js - 如何处理我已经构建的 react 应用程序?
- file - 检查目录中是否存在多个文件时需要二进制运算符
- r - 闪亮的文件输入接受所有文件类型
- http - Postman 用隐形 reCaptcha 模拟登录网站
- mysql - 无法从 kubernetes 连接到本地计算机上的 mysql
- spring-boot - SpringBoot restcontroller如何防止并发访问
- apache-spark - 当我将 event_timestamp 列从字符串转换为时间戳时,PySpark(version 3.0.0) to_timestamp 返回 null
- reactjs - 在 React 中不向子组件传递值的道具
- spring-boot - 在不使用配置文件的情况下覆盖 Spring 属性