首页 > 解决方案 > 如果 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”。我不知道为什么在这种情况下重定向不起作用,请帮忙。

标签: javascriptreactjsredirectreact-router

解决方案


你不能在函数中间调用 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>
  )
};

推荐阅读