“未捕获的类型错误:history.push 不是函数";发生错误 [英] "Uncaught TypeError: history.push is not a function" error occurs

查看:71
本文介绍了“未捕获的类型错误:history.push 不是函数";发生错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在开发导航栏.我写了一个函数来切换屏幕并在按钮 onClick 中调用它.我也将组件包裹在 withRouter 中.但是出现如下错误:

I have been developing a navigation bar. I wrote a function to switch screens and call it in button onClick. I wrapped the component in withRouter also. But the following error occurs:

未捕获的类型错误:history.push 不是函数"错误.

Uncaught TypeError: history.push is not a function" error.

这是我的代码:

import { withRouter } from 'react-router-dom';

function Navigation(history) {
  const abc = path => {
    history.push(path);
  };

return(
<button onClick={() => abc('/user')}>User</button>
);}

export default withRouter(Navigation);

谢谢

推荐答案

你已经用 withRouter 包裹了 Navigation 组件,因此你需要通过组件的道具.你可以选择分解你的道具,如下所示:

You have wrapped the Navigation component with withRouter, thus you will need to access the history object via the component's props. You may choose to destructure your props as shown below:

function Navigation({ history }) {
  const abc = path => {
    history.push(path);
  };

  return (
    <button onClick={() => abc('/user')}>User</button>
  );
}

export default withRouter(Navigation);

由于您正在使用功能组件,因此另一种处理方式是使用 useHistory 钩子,这样您就无需使用 withRouter:

Since you are working with functional components, an alternative way of doing things would be to make use of the useHistory hook, which spares you the need to wrap your component with withRouter:

import { useHistory } from 'react-router-dom';

function Navigation(props) {
  const history = useHistory();

  const abc = path => {
    history.push(path);
  };

  return (
    <button onClick={() => abc('/user')}>User</button>
  );
}

export default Navigation;

这篇关于“未捕获的类型错误:history.push 不是函数";发生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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