如何在类组件中使用react-router-dom v6导航

Jav*_*vid 30 javascript reactjs

我安装了react-router-dom v6,我想使用基于类的组件,在以前版本的react-router-dom v5中,this.props.history()在执行某些操作后可用于重定向页面,但此代码不适用于 v6 。

在react-router-dom v6中有一个useNavigate功能组件的钩子,但我需要在类基础组件中使用它,请帮助我如何在类组件中使用导航?

小智 50

在react-router-dom v6中,对历史记录的支持已被弃用,取而代之的是引入了导航。如果您想在特定事件成功时将用户重定向到特定页面,请按照以下步骤操作:

创建一个名为 的文件withRouter.js,并将下面给出的代码粘贴到该文件中:

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

export const withRouter = (Component) => {
  const Wrapper = (props) => {
    const navigate = useNavigate();
    
    return (
      <Component
        navigate={navigate}
        {...props}
        />
    );
  };
  
  return Wrapper;
};
Run Code Online (Sandbox Code Playgroud)

现在,在您想要将用户重定向到特定路径/组件的任何基于类的组件中,导入上述withRouter.js文件并使用this.props.navigate('/your_path_here')重定向函数。

为了帮助您,下面给出了显示相同内容的示例代码:

import React from 'react';
import {withRouter} from '.your_Path_To_Withrouter_Here/withRouter';

class Your_Component_Name_Here extends React.Component{
    constructor(){
        super()
        this.yourFunctionHere=this.yourFunctionHere.bind(this);
    }

    yourFunctionHere()
    {
        this.props.navigate('/your_path_here')
    }

    render()
    {
        return(
            <div>
              Your Component Code Here 
            </div>
        )
    }
}

export default withRouter(Your_Component_Name_Here);
Run Code Online (Sandbox Code Playgroud)

上面的代码工作完美。这只是一个小的扩展。如果你想要 onclick 函数,这里是代码:

<div className = "row">
    <button className= "btn btn-primary" 
            onClick={this.yourFunctionHere}>RedirectTo</button>
</div>
Run Code Online (Sandbox Code Playgroud)


小智 9

在用于重定向用户的类基组件中,请遵循以下步骤:首先导入一些像这样的组件

import { Navigate } from "react-router-dom"
Run Code Online (Sandbox Code Playgroud)

现在为“返回布尔值”创建一个状态,如下所示:

state = {
    redirect:false
}
Run Code Online (Sandbox Code Playgroud)

现在将 Naviagate 组件插入组件树的底部,但使用 && 进行条件渲染,如下所示:

{ 
   this.state.redirect && <Navigate to='/some_route' replace={true}/>
}
Run Code Online (Sandbox Code Playgroud)

现在,当您想要将用户重定向到某个页面时,只需在您想要的代码行上设置真正的重定向状态,现在您可以看到您导航到某个页面:)


and*_* o. 7

尝试这个:

import {
    useLocation,
    useNavigate,
    useParams
  } from "react-router-dom";

  export const withRouter = (Component) =>  {
    function ComponentWithRouterProp(props) {
      let location = useLocation();
      let navigate = useNavigate();
      let params = useParams();
      return (
        <Component
          {...props}
          router={{ location, navigate, params }}
        />
      );
    }
    return ComponentWithRouterProp;
  }
Run Code Online (Sandbox Code Playgroud)

就我而言,只是使用了这个函数:

import { withRouter } from '../utils/with-router';
import './menu-item.styles.scss';


const MenuItem = ({title, imageUrl, size, linkUrl,router}) =>(
    <div
        className={`${size} menu-item`} onClick={() => router.navigate(`${router.location.pathname}${linkUrl}`)}
    >
        <div className='background-image' 
        style={{
            backgroundImage: `url(${imageUrl})`
        }}  />

        <div className="content">
            <h1 className="title">{title.toUpperCase()}</h1>
            <span className="subtitle">SHOP NOW</span>
        </div>
    </div>
)

export default withRouter(MenuItem);
Run Code Online (Sandbox Code Playgroud)

我在这里找到了这个解决方案https://www.reactfix.com/2022/02/fixed-how-can-i-use-withrouter-in-react.html

其他解决方案是 useNavigate,例如:

 <button onClick={() => {navigate("/dashboard");}} >
        Dashboard
  </button>
Run Code Online (Sandbox Code Playgroud)


Mar*_*arc 6

在 React 类组件中使用<Navigate>。来自反应路由器文档:

<Navigate> 元素在渲染时会更改当前位置。它是 useNavigate 的组件包装器,并接受所有相同的参数作为 props。