我收到一个错误 Uncaught TypeError: Cannot read properties of undefined (reading 'push')

问题描述 投票:0回答:2
const ProductScreen = ({ history }) => {
  ...

  const addToCartHandler = () => {
    history.push(`/cart/${id}?qty=${qty}`)
  };

这是代码,我知道这部分代码有问题,但不知道如何解决。

我正在使用

[email protected]
。我尝试使用
this.context
this.prop
但他们也抛出错误。这样使用道具有问题吗?

这是我的 github link 文件。

javascript reactjs react-router react-router-dom react-props
2个回答
0
投票

react-router-dom@6
删除了RRDv5中之前存在的route props,没有通过
history
match
location
)prop。导入并使用
useNavigate
钩子来访问可以在回调函数中调用的
navigate
函数。

例子:

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

const ProductScreen = () => {
  const navigate = useNavigate();

  ...

  const addToCartHandler = () => {
    navigate(`/cart/${id}?qty=${qty}`)
  };

  ...

};

-1
投票

在您的组件中定义

let history = useHistory();
以使用history.push .
参考useHistory文档

© www.soinside.com 2019 - 2024. All rights reserved.