【发布时间】:2021-08-11 04:43:54
【问题描述】:
我在单独的 js 文件中有一个函数,用于检查从 Api 请求收到的状态代码,并且根据代码,该函数需要执行一些操作:
function handleResponseCodes(res) {
try {
if (res.status ===200 ) {
return res.json();
} else if (res.status === 404) {
// here I need to redirect to /help
} else if (!res.ok) {
alert("Error")
} else {
if (res.ok) {
return res.data;
}
}
} catch (error) {
console.log(error);
}
}
然后这个函数像这样与 fetch 请求一起使用。(项目将有 100+ api 请求,因此这种方式使过程易于遵循)。
fetch(url, obj)
.then((res) => handleResponseCodes(res)
如果 res.code === 404 我需要将用户重定向到 /help url,问题是当我尝试像这样使用 useHistory() 挂钩时:
import {useHistory) from 'react-router-dom'
const history = useHistory()
//and in the function
else if (res.status === 404) {
// here I need to redirect to /help
history.push("/help")
我收到错误消息说 useHistory 挂钩只能在功能组件中使用。有没有一种 React 方法可以将用户从外部功能组件重定向/推送到 /help?(基本上从函数内部)
【问题讨论】:
标签: javascript reactjs redirect react-hooks browser-history