【问题标题】:Uncaught TypeError: (0 , react_router_dom__WEBPACK_IMPORTED_MODULE_2__.useHistory) is not a function (React.js) [duplicate]未捕获的TypeError:(0,react_router_dom__WEBPACK_IMPORTED_MODULE_2__.useHistory)不是函数(React.js)[重复]
【发布时间】:2022-02-07 11:15:23
【问题描述】:

我使用 React Router Version 6 然后我在下面运行了这段代码:

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

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

Test();

但是我收到了这个错误:

未捕获的 TypeError: (0 , react_router_dom__WEBPACK_IMPORTED_MODULE_2__.useHistory) 不是 功能

我的代码有错误吗?

【问题讨论】:

    标签: javascript node.js reactjs react-router react-router-dom


    【解决方案1】:

    对于 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();
    

    【讨论】:

      猜你喜欢
      • 2017-01-26
      • 1970-01-01
      • 2019-09-15
      • 2018-11-12
      • 2022-01-18
      • 2018-07-14
      • 1970-01-01
      • 2022-07-09
      • 1970-01-01
      相关资源
      最近更新 更多