【问题标题】:How to use useHistory() hook outside functional component in React js?如何在 React js 中使用功能组件外部的 useHistory() 钩子?
【发布时间】: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


【解决方案1】:

你也可以使用document.location.href = '/help'

【讨论】:

    【解决方案2】:

    您可以像这样将历史记录作为参数传递

    ...inside function component
    const history = useHistory();
    console.log(history)
    //call function here
    yourFunc(history)
    

    【讨论】:

    • 我试过了(比如history.push),它说无法读取未定义的推送。
    • 您可以尝试在函数调用之前记录历史记录并告诉我它说了什么。
    【解决方案3】:

    好问题。我们有这么多的 api 调用,必须相应地处理这些响应。 这里我想说的是路由和UI(例如ProfilePage组件)之间的密切关系。

    根据Hook rules,我们不能在React组件之外使用钩子函数,所以我们必须使用@Zhang和@istar的答案之类的方式。

    但是拆分路由和组件并不是一个好习惯。当然有些开发者使用路由配置文件进行路由,但是更改 url 通常是在组件中完成的。 我认为路由也是组件的一部分。

    所以我想推荐你在组件内部进行路由。请取响应处理函数的结果,并根据其结果进行路由。

    【讨论】:

      猜你喜欢
      • 2021-04-13
      • 2019-12-08
      • 1970-01-01
      • 2021-04-13
      • 2023-03-25
      • 2019-08-06
      • 2022-09-23
      • 1970-01-01
      • 2020-02-13
      相关资源
      最近更新 更多