【问题标题】:I am not able to use useHistory function in action creator file我无法在动作创建者文件中使用 useHistory 函数
【发布时间】:2021-07-24 14:51:35
【问题描述】:

我正在使用 react-router-dom 和 redux。我在调度后使用 history.push("/") 但它显示错误。 我希望用户在成功验证后导航到“/”(使用 GOOGLE)

    export const googleLogin = () => async (dispatch) => {
  try {
    const response = await auth.signInWithPopup(provider);
    const doc = await db.collection("users").doc(response.user.uid).get();

    if (doc.exists) {
      await db
        .collection("users")
        .doc(response.user.uid)
        .set(
          {
            accountDetail: {
              emailVerified: response.user.emailVerified,
              photoURL: response.user.photoURL,
            },
          },
          { merge: true }
        );
history.push("/")
    } else {
      await db
        .collection("users")
        .doc(response.user.uid)
        .set({
          accountDetail: {
            userId: response.user.uid,
            displayName: response.user.displayName,
            email: response.user.email,
            photoURL: auth.currentUser.photoURL,
            accountCreatedAt: Date.now(),
          },
        });
history.push("/")
    }
      } catch (error) {
        await dispatch({ type: AUTH_ERROR, payload: error.message });
      }
    };

【问题讨论】:

  • 错误:- 无效的挂钩调用。 Hooks 只能在函数组件的主体内部调用。这可能是由于以下原因之一: 1. 你可能有不匹配的 React 版本和渲染器(例如 React DOM) 2. 你可能违反了 Hooks 规则 3. 你可能有多个 React 副本同一个应用程序请参阅reactjs.org/link/invalid-hook-call 以获取有关如何调试和修复此问题的提示。在继续之前再次检查

标签: reactjs redux react-redux react-router


【解决方案1】:

你不能在你的 action creator 文件中使用useHistory 钩子,因为它既不是 React 函数组件也不是自定义钩子。

根据rules of hooks,一个 React Hook,例如useHistory,只能用于函数组件或自定义钩子中。

但是,如果您想在 React 组件之外访问 history 对象,您可以创建自己的 history 对象并将其提供给 Router(来自 react-router-dom),如下所示:

创建一个文件,history.js:

import { createBrowserHistory } from 'history'

export default createBrowserHistory()

使用Router 并将您的history 对象提供给它:

import history from '../path/to/history'
import { Router } from 'react-router-dom'

// ...

return (
  <Router history={history}>
    <App/>
  </Router>
)

现在,您可以在动作创建者文件中轻松导入和使用history

任何 js 文件:

import history from '../path/to/history'

// ...

history.push("/some/path")

相关:Why is 'history' necessary in the Router of React-Router-Dom?


注意: 使用Router 并不会阻止您像通常使用的那样使用useHistory 钩子或withRouter HOC,即您仍然可以在其他 React 组件中使用钩子或 HOC获取history

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多