簡體   English   中英

如何在 class 組件中使用 react-router-dom v6 navigate

[英]How to use react-router-dom v6 navigate in class component

我安裝了 react-router-dom v6,我想使用基於 class 的組件,在以前版本的 react-router-dom v5 中, this.props.history()在執行某些操作后用於重定向頁面,但此代碼不適用於 v6。

在 react-router-dom v6 中有一個用於功能組件的鈎子useNavigate但我需要在 class 基本組件中使用它,請幫助我如何在 class 組件中使用導航?

在 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;
};

現在,無論您希望在哪個基於 class 的組件中將用戶重定向到特定路徑/組件,都將上面的withRouter.js文件導入那里並使用this.props.navigate('/your_path_here') function 進行重定向。

為了您的幫助,下面給出了顯示相同的示例代碼:

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);

上面的代碼工作完美。 這只是一個小的擴展。 如果你想要 onclick function 這里是代碼:

<div className = "row">
    <button className= "btn btn-primary" 
            onClick={this.yourFunctionHere}>RedirectTo</button>
</div>

在用於重定向用戶的 class 基礎組件中,請按照以下步驟操作:首先導入一些像這樣的組件

import { Navigate } from "react-router-dom"

現在制作一個 state 以返回一個 boolean 值,如下所示:

state = {
    redirect:false
}

現在將 Naviagate 組件插入到組件樹的底部,但使用 && 進行條件渲染,如下所示:

{ 
   this.state.redirect && <Navigate to='/some_route' replace={true}/>
}

現在,當您想要將用戶重定向到某個頁面時,只需在您想要的一行代碼上進行真正的重定向 state 現在您可以看到您導航到某個頁面:)

在反應 class 組件中使用<Navigate> 從反應路由器文檔:

<Navigate> 元素在呈現時會更改當前位置。 它是一個圍繞 useNavigate 的組件包裝器,並接受所有相同的 arguments 作為道具。

嘗試這個:

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;
  }

在我的情況下,剛剛使用了這個 function:

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);

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

其他解決方案是使用導航,例如:

 <button onClick={() => {navigate("/dashboard");}} >
        Dashboard
  </button>

嘗試創建一個可重用的功能組件,例如一個簡單的按鈕,您可以在 class 組件中使用它。

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

const NavigateButton = ( { buttonTitle, route,isReplaced}) => {
    const navigate = useNavigate();
    return (
        <button 
            className = "btn btn-primary" 
            onClick = { () => { 
                navigate( route , {replace:isReplaced} )
            }}
        >
            {buttonTitle}
        </button>;
        );

    });
export default NavigateButton;

在此之后,您可以在任何 class 組件中使用NavigateButton 它會起作用。

<NavigateButton title = {"Route To"} route = {"/your_route/"} isReplaced = {false}/>

從 GitHub react-router 問題線程中找到此解釋,這解釋了如何將 react-router 6 與 class 組件一起使用https://github.com/remix-run/react-router/issues/8146

我從上面的問題解釋中得到了這段代碼

import React,{ Component} from "react";
import { useNavigate } from "react-router-dom";

export const  withNavigation = (Component : Component) => {
  return props => <Component {...props} navigate={useNavigate()} />;
} 

//classComponent  
class LoginPage extends React.Component{

submitHandler =(e) =>{
    //successful login 
    this.props.navigate('/dashboard');
  }
}
 export default withNavigation(LoginPage);

這是我的解決方案:

import React, { Component } from "react";
import { useNavigate } from "react-router-dom";
class OrdersView extends Component {
    Test(props){
      const navigate = useNavigate();
      return(<div onClick={()=>{navigate('/')}}>test{props.test}</div>);
    }
  render() {
    return (<div className="">
              <this.Test test={'click me'}></this.Test>
            </div>);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM