【问题标题】:How to navigate in reactJs如何在 reactJs 中导航
【发布时间】:2021-11-16 00:55:25
【问题描述】:

我想在 ReactJS 中从一个页面导航到另一个页面我正在使用 history.push 但它给了我一个错误 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;

这是我的 login.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 成功后它应该将我导航到仪表板页面,但它没有,它会发出警报它正在工作,并且还会发出用户电子邮件和密码不匹配的警报,如果有任何一个,我将非常感激你可以帮我解决这个问题

【问题讨论】:

标签: javascript reactjs react-router react-navigation


【解决方案1】:

你需要拥有的几样东西:

  1. 基地路由器(Check here 以便更好地理解)
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(这对于在&lt;Router&gt;下渲染的组件是正确的)
import {useHistory} from 'react-router-dom'

const YourFunctionComponent = props => {

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

【讨论】:

  • 我使用了这段代码,但它仍然没有转到下一页,虽然 URL 发生了变化,但页面仍然相同,我使用的代码与您在此处编写的相同。跨度>
  • 您是否将您尝试使用的path 包含为&lt;Route path=...
【解决方案2】:

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

import { useHistory } from "react-router-dom";

// in component

const history = useHistory();
history.push('/url')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 2022-01-21
    • 2017-10-14
    • 2017-05-23
    • 1970-01-01
    • 2016-10-27
    • 2019-08-28
    相关资源
    最近更新 更多