使用 react-router-dom v6 中的历史记录

163

我使用react-router-domv6版本,当我使用this.props.history.push('/UserDashboard')时它不能工作。我把它改成了

const history = createBrowserHistory();
history.push('/UserDashboard')

但我仍然有一个问题,当我想重定向到/UserDashboard时,只有链接会改变,页面仍然是第一个页面?

有任何帮助吗?**

        handleSubmit(event){
       
    
        event.preventDefault();
        const history = createBrowserHistory();
        axios({
          method: "POST", 
          url:"http://localhost:3001/users/login", 
          data:  this.state
        }).then((response)=>{
          console.log(response.data.user.admin)
          if (response.data.success === true && response.data.user.admin === false){
           
                  const history = createBrowserHistory();
                  history.push({
                   pathname:"/users",
                   state:{
                   Key : response.data.user }
     });
    
        
           
          }else if(response.statusCode === 401 ){
            alert("Invalid username or password");
           window.location.reload(false);
          }
        })
      }

我的routes.js文件:

    import React from 'react';
    import { Navigate } from 'react-router-dom';
    import DashboardLayout from './Pages/DashboardLayout';
    import AccountView from './Pages/views/account/AccountView';
    import CustomerListView from './Pages/views/customer/CustomerListView';
    import DashboardView from './Pages/views/reports/DashboardView';
    import ProductListView from './Pages/views/product/ProductListView';
    import SettingsView from './Pages/views/settings/SettingsView';
    import Home from './Pages/home';
    import About from './Pages/About';
    import Partners from './Pages/Partners';
    import Services from './Pages/services';
    import Login from './Pages/Login';
    import RD from './Pages/RD';
    import ContactUs from './Pages/contactus';
    import Apply from './Pages/apply';
    import PartnerShip from './Pages/partnership';
    import News from './Pages/News';
    const routes = [
     {
     path: 'users',
     element: <DashboardLayout />,
     children: [
      { path: 'account', element: <AccountView /> },
      { path: 'customers', element: <CustomerListView /> },
      { path: 'dashboard', element: <DashboardView /> },
      { path: 'products', element: <ProductListView /> },
      { path: 'settings', element: <SettingsView /> }
      ]
     },
    {
    path: '/',
    element: <Home />,
    },
    {
    path: 'about',
    element: <About />
    },
     {path: 'partners',
     element: <Partners />,
    
    },
    {
    path: 'services',
    element: <Services />,
    
    },
    {
    path: 'contactus',
    element: <ContactUs />,
    
    },
    {
    path: 'login',
    element: <Login />,
    
     },{
    path: 'RD',
    element: <RD />,
    
    },
    {
    path: 'apply',
    element: <Apply />,
    
     },
     {
    path: 'partnership',
    element: <PartnerShip />,
    
     },
     {
    path: 'News',
    element: <News />,
    
     }
    ];

    export default routes;

你尝试过在函数组件或类的开头更改 const history = createBrowserHistory() 吗? - Rodolfo Campos
是的,但它不起作用。 - zineb
你是否在使用 useHistory 钩子?因为你需要在 import { useHistory } from 'react-router-dom'; 中声明它并像这样使用它: const history = useHistory() - Rodolfo Campos
你能否编辑你的代码并放置你的路由文件? - Rodolfo Campos
不,问题在于我使用的是react-router-dom@6版本,因此当我使用useHistory()时,会出现以下错误:尝试导入错误:'useHistory'未从'react-router-dom'导出。 - zineb
你可以尝试使用路径“/users”而不是“users”吗? - Raj Thakar
16个回答

185

在 react-router-dom v6 中,你需要使用 useNavigate 而不是 useHistory。

请参见以下示例:https://reacttraining.com/blog/react-router-v6-pre/

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

function App() {
  let navigate = useNavigate();
  let [error, setError] = React.useState(null);

  async function handleSubmit(event) {
    event.preventDefault();
    let result = await submitForm(event.target);
    if (result.error) {
      setError(result.error);
    } else {
      navigate('success');
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      // ...
    </form>
  );
}

36
问题是,我们如何从外部组件中进行导航?例如,当我们的逻辑在“actions”中时? - Eduard
1
@ Eduard 看一下我的回答。这应该解决你的问题。 - Poyoman
只是顺便提一下,你可以像使用 useHistory 一样告诉路由器推送 URL 或重定向 URL。为此,你可以使用 replace 对象(它将替换为你的 URL),就像这样:navigate('success' , {replace: true}); - Rman__
让?为什么不用const? - Pablo Recalde

37

基于 react-router-dom 的源代码,你可以像下面这样做:

// === Javascript version  === //

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

const CustomRouter = ({
  basename,
  children,
  history,
}) => {
  const [state, setState] = React.useState({
    action: history.action,
    location: history.location,
  });

  React.useLayoutEffect(() => history.listen(setState), [history]);

  return (
    <Router
      basename={basename}
      children={children}
      location={state.location}
      navigationType={state.action}
      navigator={history}
    />
  );
};
// === typescript version === //
    
import * as React from "react";
import { BrowserHistory } from "history";
import { Router, Navigator } from "react-router-dom";

type Props = {
  basename?: string;
  children: React.ReactNode;
  history: BrowserHistory;
}

const CustomRouter = ({ basename, children, history }: Props) => {
  const [state, setState] = React.useState({
    action: history.action,
    location: history.location,
  });
  
  React.useLayoutEffect(() => history.listen(setState),[history])

  return (
    <Router
      basename={basename}
      location={state.location}
      navigator={history}
      navigationType={state.action}
    >
      {children}
    </Router>
  );
};

然后让你的历史来自外部:

import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

<CustomRouter history={history}>
  ...
</CustomRouter>

嘿 @poyoman,你如何使用基于类的组件实现相同的功能。我不使用函数式组件。 - Fonty
1
@Fonty 只需将我的功能组件放入您的类组件的“render”方法中即可 :) - Poyoman
1
谢谢@poyoman,我会尝试一下。使用最新版本会更好。 - Fonty
我正在使用TypeScript,Navigator中没有action、location和listen,只有4个方法——createHref、go、push和replace。 - gavr

23

我们都知道在react-router-dom v6中已经不存在 { useHistory } 这个东西了,现在有更好的方法来完成 useHistory 的工作。

首先需要导入 useNavigate ...

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

导入后只需执行以下操作即可

function Test() {
    const history = useNavigate();

    function handleSubmit(e) {
        e.preventDefault();

        history('/home');
    }

    return (
        <form onSubmit={handleSubmit}>
            <button>Subimt</button>
        </form>
    )
}

9
你刚才使用了“history”作为变量名,但实际上这并没有使它持有浏览器历史记录对象。如果你使用任何有效的变量名代替“history”,这个代码也会同样工作。 - Subham Saha

10

Reactjs v6已经使用useNavigate代替了useHistory。

=>首先,你需要像这样导入它:import { useNavigate } from 'react-router-dom'。

=>然后你只能在React函数组件下使用它,例如:

const navigate = useNavigate();

=>接下来,你只需要像这样输入要跳转的路由名称:

navigate("/about");

例如:如果你想在点击按钮后跳转到关于页面,那么你应该在onClick事件下添加navigate("/about")

<button onClick = {()=>navigate("/about")}>去关于页面

谢谢。


7

如何在 react-router-dom v6 中使用 useNavigate

import {useNavigate} from 'react-router-dom';
const navigate = useNavigate();
navigate('/home')

6

基于@Poyoman的答案,创建一个Typescript自定义BrowserRouter组件:

创建CustomBrowserRouter组件:

import React from "react";
import { BrowserHistory, Action, Location } from "history";
import { Router } from "react-router-dom"

interface CustomRouterProps {
    basename?: string,
    children?: React.ReactNode,
    history: BrowserHistory
}

interface CustomRouterState {
    action: Action,
    location: Location
}

export default class CustomBrowserRouter extends React.Component<CustomRouterProps, CustomRouterState> {
    constructor(props: CustomRouterProps) {
        super(props);
        this.state = { 
            action: props.history.action,
            location: props.history.location
        };

        React.useLayoutEffect(() => props.history.listen(this.setState), [props.history]);
    }

    render() {
        return (
            <Router
                basename={this.props.basename}
                children={this.props.children}
                location={this.state.location}
                navigationType={this.state.action}
                navigator={this.props.history}
            />
        );
    }
}

使用CustomBrowserRouter:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { createBrowserHistory } from "history";
import CustomBrowserRouter from './CustomRouter/CustomBrowserRouter';

let history = createBrowserHistory();

ReactDOM.render(
  <React.StrictMode>
    <CustomBrowserRouter history={history}>
      <App />
    </CustomBrowserRouter>
  </React.StrictMode>,
  document.getElementById('root')
);

1
你的类在继承对象中使用了钩子,这在React中是不允许的钩子规则。我使用了一个函数来使它工作。 - Adnan
错误地点赞了这个。就像N0xB0DY所说的那样,你不能在基于类的组件中使用钩子。 - cdeutsch

5

解决方案是

在v6版本中,该应用程序应该重写以使用导航API。大部分情况下,这意味着将useHistory更改为useNavigate,并更改history.push或history.replace调用点。

    // This is a React Router v5 app
import { useHistory } from "react-router-dom";
        
        function App() {
          let history = useHistory();
          function handleClick() {
            history.push("/home");
          }
          return (
            <div>
              <button onClick={handleClick}>go home</button>
            </div>
          );
        }

查看该文章:https://reactrouter.com/en/v6.3.0/upgrading/v5#use-usenavigate-instead-of-usehistory

// This is a React Router v6 app
import { useNavigate } from "react-router-dom";

function App() {
  let navigate = useNavigate();
  function handleClick() {
    navigate("/home");
  }
  return (
    <div>
      <button onClick={handleClick}>go home</button>
    </div>
  );
}

导航时无需使用pushreturn

3

我无法完全搞定@Reid Nantes的版本,因此将其转换为一个功能组件,现在它可以很好地工作了。

import React from "react";
import { BrowserHistory, Action, Location } from "history";
import { Router } from "react-router-dom";

interface CustomRouterProps {
    basename?: string;
    children?: React.ReactNode;
    history: BrowserHistory;
}

interface CustomRouterState {
    action: Action;
    location: Location;
}

export const CustomBrowserRouter: React.FC<CustomRouterProps> = (props: CustomRouterProps) => {
    const [state, setState] = React.useState<CustomRouterState>({
        action: props.history.action,
        location: props.history.location,
    });

    React.useLayoutEffect(() => props.history.listen(setState), [props.history]);
    return <Router basename={props.basename} children={props.children} location={state.location} navigationType={state.action} navigator={props.history} />;
};


3
如果您仍在使用React v6+中的类组件,则另一种解决方案是将新的导航对象作为history注入。这可以解决无法在类组件中使用的麻烦问题,尽管您应该尝试将来远离类组件。我发现我的一个大型代码库陷入了这种困境,我相信其他人仍然会遇到同样的问题。
import React, { Component } from "react";
import { useNavigate } from "react-router-dom";

class MyClass extends Component {
  handleClick(e) => {
    this.props.history('place-to-route');
  }
}
export default (props) => (
  <MyClass history={useNavigate()} />
);

2

最好使用一个模块:

let _navigate
export const navigate = (...args) => _navigate(...args)
export const useNavigateSync = () => {
   _navigate = useNavigate()
}

在您的顶层组件中运行useNavigateSync。 在您的代码中的任何位置导入navigate


好主意!然而,在组件外部使用“useNavigate”即钩子并不符合React的规范,我不确定这是否是一个干净的解决方案。 - Poyoman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接