我已经使用 firebase\react 进行了登录\注册身份验证,如果登录或注册正确,我正在尝试将用户定向到下一页。但我不断收到上述错误“错误:类型错误:无法读取未定义的属性“推送”。我猜想在何处以及如何调用 history.push 存在问题。有人可以提供快速修复吗?低于我的代码的一部分。
App.js
import React, { useEffect, useState } from "react";
import "./App.css";
import Contacts from "./components/Contacts";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import HomePage from "./components/HomePage";
import Login from "./components/Login";
import { useHistory } from "react-router-dom";
import { auth } from "./firebase";
const App = () => {
const history = useHistory();
const [user, setUser] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [emailError, setEmailError] = useState("");
const [passwordError, setPasswordError] = useState("");
const [hasAccount, setHasAccount] = useState(false);
const clearInputs = () => {
setEmail("");
setPassword("");
};
const clearErrors = () => {
setEmailError("");
setPasswordError("");
};
const handleLogin = () =>{
clearErrors();
auth.signInWithEmailAndPassword(email, password)
.then((u) => {
console.log('successfully logged in')
history.push('/HomePage')
})
.catch((err) => {
console.log("Error:" + err.toString());
});
};
const handleSignup = () => {
clearErrors();
auth
.createUserWithEmailAndPassword(email, password)
.then((u) => {
console.log("successfully signed up");
history.push('/HomePage')
})
.catch((err) => {
console.log("Error:" + err.toString());
});
};
const authListener = () => {
auth.onAuthStateChanged((user) => {
if (user) {
clearInputs();
setUser(user);
} else {
setUser("");
}
});
};
useEffect(() => {
authListener();
}, []);
return (
<Router>
<div className="row">
<div className="col-md-8 offset-md-2">
<Switch>
<Route exact path="/HomePage">
<HomePage />
</Route>
<Route exact path="/">
<Login
email={email}
setEmail={setEmail}
setPassword={setPassword}
password={password}
handleLogin={handleLogin}
handleSignup={handleSignup}
emailError={emailError}
passwordError={passwordError}
hasAccount={hasAccount}
setHasAccount={setHasAccount}
/>
</Route>
<Route exact path="/Contacts">
<Contacts />
</Route>
</Switch>
</div>
</div>
</Router>
);
};
export default App;
答案 0 :(得分:0)
<Router>
组件应该比这个组件高一级。否则你将无法访问历史。 useHistory
仅适用于已经在 <Router>
中的组件。无论您在哪里使用 <App />
,您都可以将其包装在 .it 中,应该是
<Router><App /></Router>