reactjs - 如何将其转换为使用我已经到位的代码?
问题描述
我已经成功地将我的大部分代码转换为带有 Node 的 React Hooks,用于向/从 mysql db 写入/读取的服务器。但是,我需要能够以某种方式使用此代码来验证用户名和密码:
if (this.state.username === "Tim" && this.state.password === "1234") {
AuthenticationService.registerSuccessfulLogin(
this.state.username,
this.state.password
);
this.props.history.push(`/welcome/${this.state.username}`);
} else {
this.setState({ showSuccessMessage: false });
this.setState({ hasLoginFailed: true });
}
}
这是我需要使它工作的代码:
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [loginStatus, setLoginStatus] = useState("");
const login = () => {
Axios.post("http://localhost:3000/login", {
username: username,
password: password,
}).then((response) => {
if (response.data.message) {
setLoginStatus(response.data.message)
} else {
setLoginStatus(response.data[0].username)
}
});
};
这是我尝试过的,但不起作用:
useEffect(() => {
const navigate = async () => {
const authorized = await
AuthenticationService.registerSuccessfulLogin;
if (username === "Tim" && password === "1234" && authorized) {
history.push(`/welcome/${username}`);
} else if (!authorized) {
history.push("/login");
}
};
navigate();
},[username,password,history])
解决方案
这是有效的:
const history = useHistory();
const login = () => {
Axios.post("http://localhost:3000/login", {
username: username,
password: password,
}).then((response) => {
if (response.data.message) {
setLoginStatus(response.data.message)
} else {
setLoginStatus(response.data[0].username)
AuthenticationService.registerSuccessfulLogin(
username,
password
);
history.push(`/welcome/${username}`);
}
});
};
推荐阅读
- node.js - 通过 API 网关连接微服务(使用 Websocket)和 Websocket 客户端浏览器应用程序
- javascript - 如何为 NestJS 中的每个新 HTTP 请求使用新实例?
- html - 自动调整 div
- selenium - Selenium 创建批量电子邮件地址
- python - 在 python 中,不能删除句点 '.'
- objective-c - React Native 桥(从 react 到 iOS 的交互)
- javascript - javascript将div的内容从画布复制到剪贴板不再适用于Firefox
- javascript - React & Moment JS - 如何仅映射即将到来的日期?
- php - 从选项 1 开始 $io->choice()
- java - 如何知道java exp中的字符