React-Router:为什么在 React 中未定义 useHistory? [英] React-Router: Why is the useHistory undefined in react?

查看:335
本文介绍了React-Router:为什么在 React 中未定义 useHistory?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个.它与文档中所说的完全相同.我认为 react-router-dom 模块很好,因为在其他组件中,BrowserRouter、Router 和 Link 对我有用

I have this. It is exactly the same as it says in the documentation. I think the react-router-dom module is fine because in other components the BrowserRouter, Router and Link work for me

import { useHistory } from "react-router-dom"
import React from 'react'

export default function HomeButton() {
  let history = useHistory()

  function handleClick() {
    history.push("/home")
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

当我点击按钮时会发生这种情况

when I click the button this happens

TypeError: 无法读取未定义的属性 'push'

TypeError: Cannot read property 'push' of undefined

我是 reactjs 的新手,请帮忙,谢谢

I am newbie in reactjs please help, and thanks

推荐答案

  1. 这是因为该组件中未设置 react-router 上下文.由于它的 组件设置了上下文,您可以在子组件中使用 useHistory,但不要在子组件中使用.

  1. Its because the react-router context isn't set in that component. Since its the <Router> component that sets the context you could use useHistory in a sub-component, but not in that one.

当其中之一(RouteruseHistory 钩子)从react-router 和另一个来自 react-router-dom 和包这些软件包的版本不匹配.不要同时使用它们,

The same error can be thrown when one of them(Router and the useHistory hook) are imported from react-router and the other one from react-router-dom and the package versions of those packages don't match. Don't use both of them,

这篇关于React-Router:为什么在 React 中未定义 useHistory?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆