Uncaught TypeError: (0 , react_router_dom__WEBPACK_IMPORTED_MODULE_2__.useHistory) is not a function (React.js)

Uncaught TypeError: (0 , react_router_dom__WEBPACK_IMPORTED_MODULE_2__.useHistory) is not a function (React.js)

我使用 React Router Version 6 然后我 运行 下面的代码:

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

function Test() {
  const history = useHistory();
  history.push('/');
  history.replace('/');
  history.goBack();
}

Test();

但是我得到了这个错误:

Uncaught TypeError: (0 , react_router_dom__WEBPACK_IMPORTED_MODULE_2__.useHistory) is not a function

我的代码有没有错误?

对于 React Router 版本 6,使用 "useNavigate" 而不是 "useHistory"这是 React Router 版本 5.

所以替换你的代码(React Router Version 5):

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

function Test() {
  const history = useHistory();
  history.push('/');
  history.replace('/');
  history.goBack();
}

Test();

使用此代码(React Router 版本 6):

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

function Test() {
  const navigate = useNavigate();
  navigate('/');                    // Equivalent to "history.push('/');"
  navigate('/', { replace: true }); // Equivalent to "history.replace('/');"
  navigate(-1);                     // Equivalent to "history.goBack();"
}

Test();