在功能组件中实现props.history.push(/)时遇到错误


import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { Button } from 'react-bootstrap';
import NavBarManu from './NavBarManu'
const Login = () => {
const [name, setName] = useState("");
const [password, setPassword] = useState("");
function login() {
fetch("http://localhost:3000/login?q=" + name).then((data) => {
data.json().then((resp) => {
console.warn("resp", resp)
if (resp.length > 0) {
localStorage.setItem('login', JSON.stringify(resp))
//Facing error
console.warn(this.props.history.push('list'))
}
else {
alert("Please check username and password")
}
})
})
}
return (
<div>
<br /><h2>Please Login !</h2><br />
<input type="text"
placeholder="enter name"
name="user" onChange={(event) => setName(event.target.value)} /> <br /> <br />
<input
placeholder="enter password"
type="password" name="password" onChange={(event) => setPassword(event.target.value)} /> <br /> <br />
<button onClick={() => { login() }} >Login</button>
</div>
);
};
export default Login;

我在console.warn(this.props.history.push('list'))中遇到错误。该语法适用于类组件。这就是为什么它显示错误。我在功能组件中实现它时遇到了一些困难。在用户按下登录按钮后,我希望页面指向"列表"。页面。请有人指出我的错误,或者如果有其他更好的方法来解决这个问题,请给我建议。

您正在创建功能组件并使用类组件语法。你的道具是空的。

this关键字在类组件中用于引用状态。

应该是这样的:

console.warn(history.push('list'))

必须导入:

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

在Login组件正文中:

import { useHistory } from "react-router-dom";
const Login = () => {
const [name, setName] = useState("");
const [password, setPassword] = useState("");
const history = useHistory()
function login() {
fetch("http://localhost:3000/login?q=" + name).then((data) => {
data.json().then((resp) => {
console.warn("resp", resp)
if (resp.length > 0) {
localStorage.setItem('login', JSON.stringify(resp))
//Facing error
console.warn(history.push('list'))
}
else {
alert("Please check username and password")
}
})
})
}
return ...

最新更新