首页 > 解决方案 > 如何使用 ”“在函数内部?

问题描述

这是我的功能,因此当用户登录时,它会检查用户的密码和用户名,如果它们都正确,它应该重定向到 /note url,并通过它传递用户 ID。我见过人们在 render() 上使用它,但我想让我的 App.jsx 应用程序保持简单,我认为这是一个很好的做法。

我曾尝试使用 useHistory 方法,但是当用户输入数据时,用户需要手动刷新页面才能显示新数据。如果我添加一个 useHistory 来刷新页面,它表示 location.state 值未定义。

我该如何解决这个问题?

谢谢

// Checking to see if current user's log info exists in db
function logIn(e) {
  e.preventDefault();
  const currentUser = users.find(
    (users) => users.username === userInput.username
  );
  if (!currentUser) {
    console.log("The Username was not found. Please try again");
  } else {
    if (currentUser.password === userInput.password) {
      // history.push("./note", { userId: currentUser._id });

      return <Redirect to={"/note/" + currentUser._id} />;
    } else {
      console.log("The password is incorrect");
    }
  }
}

这是我的路由代码

import React from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";

import NoteDashboard from "./NoteDashboard";
import Home from "./Home";
import CreateAccount from "./CreateAccount";

function App() {
  return (
    <Router>
      <div className="container">
        <Switch>
          <Route exact path="/" component={Home}></Route>
          <Route path="/create" component={CreateAccount}></Route>
          <Route path="/note" component={NoteDashboard}></Route>
        </Switch>
      </div>
    </Router>
  );
}

export default App;

标签: reactjsreact-router-dom

解决方案


从函数重定向到页面的唯一(我发现)是 use ReactDOM.hydrate这里举个例子。示例有效,但只是第一次。之后,重定向停止工作。#也许是因为我不知道的某些技术原因,codesandbox 连接到 url 符号。尝试在本地应用此解决方案,让我知道是否可以多次使用。


推荐阅读