【问题标题】:how to use history instance while using react routers v6?如何在使用反应路由器 v6 时使用历史实例?
【发布时间】:2020-12-15 05:30:04
【问题描述】:

我正在使用 react-router v6,我必须使用历史实例。

我已经安装了它使用

yarn add history react-router-dom@next

使用历史实例的一种方法我猜它必须使用 v5 是使用从 react-router-dom 导入的 useHistory 钩子

此代码在 v5 上运行良好,但在 v6 上无法正常工作

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

const history = useHistory();

const onRedirectCallback = (appState) => {
        history.push(appState?.returnTo || window.location.pathname);
};

v6 版本出现此错误

尝试导入错误:“useHistory”未从“react-router-dom”导出。

【问题讨论】:

标签: javascript reactjs react-router react-router-dom


【解决方案1】:

你需要使用useNavigate钩子和新的navigate API

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

const navigate = useNavigate();

const onRedirectCallback = (appState) => {
        navigate(appState?.returnTo || window.location.pathname);
};

【讨论】:

    【解决方案2】:
    // import
    
    const { useNavigate } from 'react-router-dom'
    
    const navigate = useNavigate()
    
    navigate({ pathname: './webpage/path' }) 
    
    navigate({ pathname: './webpage/path' }, { replace: true })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-06
      • 2019-12-15
      • 2020-10-04
      • 2016-08-16
      • 2021-04-22
      • 2022-01-10
      • 2022-01-08
      • 2016-05-28
      相关资源
      最近更新 更多