javascript - 从非反应组件渲染组件
问题描述
我正在尝试从 javascript 函数呈现组件
export const fetcher = (signal, method, route, content = null) => {
return fetch(`${API_URL}${route}`, options)
.then(res => {
if (res.status === 401 && isLoggedIn())
// SHOW SNACKBAR HERE
return Promise.reject("INVALID_TOKEN");
if (res.status === 500)
// SHOW SNACKBAR HERE
return Promise.reject("UNKNOWN_ERROR");
if ((res.status < 200 || res.status >= 300) && res.status !== 401)
// SHOW SNACKBAR HERE
return Promise.reject("UNKNOWN_ERROR");
if(res.status === 204)
// SHOW SNACKBAR HERE
return res.status;
if (res.headers.get("Content-Type").indexOf("application/json") !== -1)
// SHOW SNACKBAR HERE
return res.json();
return res.status === 200 ? res.text() : res.status;
})
.catch(err => {
console.log(err, `${method?.toUpperCase()} ${route}`);
if (err === "INVALID_TOKEN") {
removeToken();
window.location = "/";
}
else if (err === "UNKNOWN_ERROR") {
window.location = "/500";
}
else if (err.name !== 'AbortError') {
window.location = '/networkerror';
}
return Promise.reject();
});
};
我尝试使用 HOC 但这对我不起作用。
是否可以在反应上下文之外渲染反应元素?
谢谢 !
解决方案
不确定这是可能的,至少在一个优雅的问题上是不可能的。
我们在获取时通常会做的是处理调用 fetch 函数的组件中的相关事件。
您可以根据函数是否在 catch 块中结束而设置相应的错误状态。然后您可以有条件地从渲染中调用所需的组件。
例如,这样的事情:
import { fetchData } from ...
export function Foo() {
const [error, setError] = useState(null);
async const onFetch = () => {
try {
...
await fetch();
} catch (error) {
setError(error);
}
}
useEffect(() => {
// Initial -
onFetch();
}, []);
return (
...
{error !== null && <SnackbarComp error={error} />}
)
}
我知道这不一定能回答你的问题。
如果没有帮助,请随意忽略。
推荐阅读
- python - 与 multiprocessing.Pool 共享一个计数器
- c# - 如何从文件中加载文本并使用c#将其放入列表中
- javascript - 发送 Chrome 桌面通知,如果
- android - java.lang.IllegalArgumentException:您无法为已破坏的活动启动加载
- php - PHP SQL $stmt->fetch() 将数组推入另一个数组
- testing - Katalon WebUI.SetMaskedText() 随机换行文本
- javascript - 如何强制服务人员清除缓存?
- git - git clone --depth 使用 https 和 bitbucket?
- apache2.4 - mod_auth_openidc 与 Apache2.4 反向代理
- python - 如何将 file.npy 加载到 numpy 数组中?