React Js 在按钮单击事件中使用 Navigate 在页面之间导航

React Js navigate between pages using Navigate inside the button click event

我正在使用最新版本的 react js。我想在登录后导航到添加页面。这是我的代码。

import React,{Component} from 'react';
import { variables } from '../../Variables';
import { Navigate } from 'react-router-dom';



export class Login extends Component{

constructor(props){
    super(props);
    this.state={
        login:[],
        name:"",
        password:"",
        redirect: false
    }
}

changelogindetailsname = (e)=>{
    this.setState({name:e.target.value})
}

changelogindetailspass = (e)=>{
    this.setState({password:e.target.value})
}

loginClick(){
    
        fetch(variables.API_URL+'login',{
            method:'POST',
            headers:{
                'Accept':'application/json',
                'Content-Type':'application/json'
            },
            body:JSON.stringify({
                name:this.state.name,
                password:this.state.password
            })
            
        })
        .then(res=>res.json())
        .then((result)=>{
            alert(result);
            const navigate = Navigate();                
          navigate("/add" , { replace: "/" } );

             
        },(error)=>{
            alert('Faild');
        })
    }


render(){
    const{
        name,
        password
    }=this.state;
    return(
            <div>
                <center>
                    <h1></h1>
                    <hr/>
                    <h3>Welcome Back !</h3>
                    <p></p>
                    <div className="container">
                        <br/>
                        <br/>
                        <br/>
                        <div className="row">
                            <div className="col">

                            </div>
                            <div className="col">

                            </div>
                            <div className="col-4">
                            <style>{"\ .rr{\ float:left;\ }\ "} </style>
                            <style>{"\ .bb{\ float:right;\ }\ "} </style>
                                <div className="mb-3">
                                    <label className="form-label rr d-flex"> Username</label>
                                    <div className="input-group input-group-lg">
                                        <input type="text" className="form-control " id="formGroupExampleInput" placeholder="Username"
                                        value={name}
                                        onChange={this.changelogindetailsname}/>
                                    </div>
                                </div>
                                <div className="mb-3">
                                    <label className="form-label rr d-flex">Password</label>
                                    <div className="input-group input-group-lg">
                                        <input type="password" className="form-control" id="formGroupExampleInput2" placeholder="Password"
                                        value={password}
                                        onChange={this.changelogindetailspass}/>
                                    </div>
                                </div>
                                <div className="d-flex mb-3">
                                    <a href="#" className="form-label rr"> Forgot your password?</a>
                                </div>
                                <div className="col">
                                        <div className="form-check rr">
                                            <input className="form-check-input" type="checkbox" value="" id="flexCheckDefault"/>
                                            <label className="form-check-label" htmlFor="flexCheckDefault">
                                                Remember me
                                            </label>
                                        </div>
                                </div>
                                   
                                <div className="col">
                                    <button type="button" className="btn btn-success bb"
                                    onClick={()=>this.loginClick()} navigate="/Add.js" >Login</button>
                                </div>
                                   
                                <br/>
                                <br></br>
                                <hr/>
                                <p>Don't have an account?</p>
                                <div className="mb-3">
                                    
                                     <button type="button" className="btn btn-light d-flex"
                                     href="Add.js" >Sign up for Muessoze</button>
                           
                                  </div>
                            </div>
                            <div className="col">
                                
                            </div>
                            <div className="col">
                                
                            </div>
                        </div>

                      
                   
                    </div>
                   
                </center>
            </div>
    )
}

}

编译没有错误,但运行时浏览器控制台出现此错误

未捕获(承诺)TypeError:无法解构“_ref2”的 属性 'to',因为它未定义。 在导航 (index.tsx:165:1) 在 Login.js:44:1

这是App.js文件代码

  import { BrowserRouter, Route, Routes } from 'react-router-  dom';
  import './App.css';
  import { Login } from './components/Login/Login';
  import { Add } from './components/Login/Add';

  function App() {
     return (
       <BrowserRouter>
          <Routes>
             <Route exact path="/" element={<Login/>}/>
             <Route exact path="/add" element={<Add/>}/>
          </Routes>
       </BrowserRouter>
     );
   }

   export default App;

我不知道该怎么办,我尝试了几次,但问题都是一样的。我认为传递参数是这个错误的原因。但我仍然没有解决办法。请帮助我。

编辑(在 OP 澄清他正在使用 class 组件之后):

由于您使用的是 class 组件,因此不能使用 Hooks (请切换到函数组件,大多数基于 class 的反应代码都是遗留代码!),但你可以用 HOC 装饰你的组件,并将 navigate 作为 prop 传递给它,我们几个小时前回答了一个非常相似的 :

HOC:

const withNavigate = Component => props => {
  const navigate = useNavigate();
  const params = useParams();

  return <Component {...props} params={params} navigate={navigate} />;
}

const LoginWithNavigate = withNavigate(Login);

然后在您的登录组件中,您只需 this.props.navigate("/") 即可进行导航。


删除const navigate = Navigate();
Navigate 是一个 React 组件,您不能那样使用它,要像那样使用导航,您需要使用 useNavigate hook 。

Import {useNavigate} from "react-router-dom"

然后在你的 React 组件中:

const navigate = useNavigate()            

现在应该可以了,只需将 replace prop 更改为布尔值即可。