如何在react中导航



我想在使用历史的ReactJS中从一个页面导航到另一个页面。但它给了我一个错误TypeError: Cannot read properties of undefined (reading 'push') at Login.jsx:65 at async loginHandel (Login.jsx:51)

这是我的App.js代码

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Login from "./components/Login";
function App() {
return (
<div className="App">
<Login />
</div>
);
}
export default App;

,这是我的登录。JSX函数代码

const loginHandel = async () => {
setLoading(true);
const data = await axios
.get(
`http://116.202.231.219:8069/Restaurant/Login_Updated?Cont4=${email}&Pswd=${password}`
)
.then((res) => {
//check the res if its getting the correct data or not?
//restructure accordingly
console.log(res);
const persons = res;
if (persons.status === 200) {
//perform any thing here
alert("It is working");
// setUser(persons);
setLoading(false);
history.push("/dashboard");
// window.open("./Dashboard.jsx")

}
})
.catch((err) => {
//handel your error
console.log(err);
alert("User email and passwoed mismatched!");
// setLoading(false);
});
};

我希望在API成功后,它应该导航到仪表板页面,但它没有,它给出了它正在工作的警报,也给出了用户电子邮件和密码不匹配的警报,如果你们中的任何人可以帮助我整理这个问题,我将非常感激

你需要的东西:

  1. 路由器的基础(检查这里更好地理解)
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom'
function App() {
return (
<div className="App">
<Router>
<Switch>
<Route path='/' component={/* Import and use your component */} />
</Switch>
</Router>
</div>
);
}
  1. 使用useHistory钩子访问history.push(这对于在<Router>下渲染的组件是正确的)
import {useHistory} from 'react-router-dom'
const YourFunctionComponent = props => {
const history = useHistory()

const letsChangeLocation = () => history.push('/wherever')
}

你需要在你的组件中导入useHistory。然后用它来导航。

import { useHistory } from "react-router-dom";
// in component
const history = useHistory();
history.push('/url')
  1. 在主基文件中定义路由

  2. 使用useHistory for react router version 5

    import { useHistory } from "react-router-dom";
    function HomeButton() {
    let history = useHistory();
    function handleClick() {
    history.push("/home");
    }
    return (
    <button type="button" onClick={handleClick}>
    Go home
    </button>
    );
    }
    

    在react router version 6中使用useNavigate

    import { useNavigate } from "react-router-dom";
    function SignupForm() {
    let navigate = useNavigate();
    async function handleSubmit(event) {
    event.preventDefault();
    await submitForm(event.target);
    navigate("../success", { replace: true });
    }
    return <form onSubmit={handleSubmit}>{/* ... */}</form>;
    }
    

相关内容

  • 没有找到相关文章

最新更新