首页 > 解决方案 > 从非反应组件渲染组件

问题描述

我正在尝试从 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 但这对我不起作用。

是否可以在反应上下文之外渲染反应元素?

谢谢 !

标签: javascriptreactjs

解决方案


不确定这是可能的,至少在一个优雅的问题上是不可能的。

我们在获取时通常会做的是处理调用 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} />}
   )
}

我知道这不一定能回答你的问题。
如果没有帮助,请随意忽略。


推荐阅读