reactjs - 如何使用 ”“在函数内部?
问题描述
这是我的功能,因此当用户登录时,它会检查用户的密码和用户名,如果它们都正确,它应该重定向到 /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;
解决方案
从函数重定向到页面的唯一(我发现)是 use ReactDOM.hydrate
。这里举个例子。示例有效,但只是第一次。之后,重定向停止工作。#
也许是因为我不知道的某些技术原因,codesandbox 连接到 url 符号。尝试在本地应用此解决方案,让我知道是否可以多次使用。
推荐阅读
- c++ - mfc图片控件多次运行后消失
- scala - 路径依赖类型(在类型和内部类上)
- python - Python 用线程同时做两件事
- python - 如果不匹配,数据框分配一揽子标准
- r - 将数据帧转换为时间序列导致字符向量被强制转换为 NA
- python - 当我有下面提到的名为 seeker 的起始节点时,如何找到与名为 target 的目标节点的距离?
- string - 如何检查字符串是否仅由 CMake 中的 ASCII 字符组成?
- ruby-on-rails - Minitest 和 Fixtures:传递正确的参数?
- c++ - 如何在动态调整大小的结构中打印所有值?C++
- python - 使用 Python 在字符串中搜索