0

我目前正在努力解决当用户单击一个将为他们注册帐户的按钮时如何重定向到主页:我当前的设置是这样的

function Application() {
    const user = useContext(UserContext);
    return (
        user ?
            <Router>
                <LandingScreen path="landingscreen"/>
             </Router>

            :
            <Router>
                <SignUp path="signUp" />
                <SignIn path="/" />
            </Router>

    );
}
export default Application;
const SignIn = () => {

    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState(null);

    const signInWithEmailAndPasswordHandler = (event,email, password) => {
        event.preventDefault();
        auth.signInWithEmailAndPassword(email, password).catch(error => {
            setError("Error signing in with password and email!");
            console.error("Error signing in with password and email", error);
        });
    };

我将如何添加一个函数 signInWithEmailAndPasswordHandler 以便在调用它时将用户重定向到 /landingscreen?我已经阅读了到达文档,但我是 JSX 的新手,并且很难实现这一点。

4

2 回答 2

0
import { useHistory } from 'react-router-dom';

const SignIn = () => {

    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState(null);
    const history = useHistory(); // Add this from redux-form

    const signInWithEmailAndPasswordHandler = (event,email, password) => {
        event.preventDefault();
        auth.signInWithEmailAndPassword(email, password).catch(error => {
            setError("Error signing in with password and email!");
            console.error("Error signing in with password and email", error);
        })
        // Add this (if you want it call only if not catched error, place it before .catch
        .then(() => {   
            history.push('/landingscreen');
        });
    };
于 2020-04-02T15:52:44.933 回答
0

您可以使用react-router-dom钩子并调用history.push('url')

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

const SignIn = () => {
    const history = useHistory()
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [error, setError] = useState(null);

    const signInWithEmailAndPasswordHandler = (event,email, password) => {
        event.preventDefault();
        auth.signInWithEmailAndPassword(email, password)
        .then(() => {
          // Logged in successfully
          history.push('/landingscreen');
        })
        .catch(error => {
            setError("Error signing in with password and email!");
            console.error("Error signing in with password and email", error);
        })
    };

于 2020-04-02T15:54:24.853 回答