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

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

问题描述

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

import { useHistory } from react-router-dom";从反应"导入反应导出默认函数 HomeButton() {让历史 = useHistory()函数 handleClick() {history.push("/home")}返回 (<按钮类型=按钮"onClick={handleClick}>回家);}

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

<块引用>

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

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

解决方案

您正在使用 将路由器添加到 DOM 中的同一组件中正在使用 useHistory.

useHistory 仅适用于子组件,但不适用于父组件或组件本身.

您必须将组件的 <Router>...</Router> 包装向上移动一级.您可以在 app.js 中执行此操作:

App.js

<代码>从'react-router-dom'导入{ BrowserRouter 作为路由器};功能应用(){返回 (<路由器>

</路由器>);}导出默认应用程序;

component.js

<代码>从'反应'导入反应;从react-router-dom"导入 {useHistory, withRouter };导出默认函数 HomeButton() {让历史 = useHistory()函数 handleClick() {history.push("/home")}返回 (<按钮类型=按钮"onClick={handleClick}>回家);}导出默认 withRouter(HomeButton);

这对我有用.

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: Cannot read property 'push' of undefined

I am newbie in reactjs please help, and thanks

解决方案

You are adding the Router to the DOM with <Router>...</Router> in the same component you are using useHistory.

useHistory will work only on child components but it won't work on parent component or the component itself.

You have to move the <Router>...</Router> wrapping of the component one level up. You can do that in the app.js:

App.js



import { BrowserRouter as Router } from 'react-router-dom'; 

function App() {
  return (
    <Router>
      <div className="App">
      </div>
    </Router>
  );
}

export default App;

component.js


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


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

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

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

export default withRouter(HomeButton);

This worked for me.

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

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