Reach Router: перенаправление на urI при нажатии функции - PullRequest
0 голосов
/ 02 апреля 2020

В настоящее время я борюсь с тем, как перенаправить на домашнюю страницу, когда пользователь нажимает кнопку, которая зарегистрирует его для учетной записи: Моя текущая настройка похожа на эту

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 и пытаюсь реализовать это.

Ответы [ 2 ]

0 голосов
/ 02 апреля 2020

Вы можете использовать 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);
        })
    };
0 голосов
/ 02 апреля 2020
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');
        });
    };
...