Как вернуть разные страницы в функциональный компонент React - PullRequest
0 голосов
/ 30 апреля 2020

Я создаю приложение реагирования, и когда мое приложение запускается, я хочу знать, вошел ли пользователь, чтобы отправить его на домашнюю страницу. Когда мое приложение запускает маршрут "/", загрузите эту страницу

import React from 'react';
import { Redirect } from 'react-router';
import { LocalStorageService } from "../services/localData-service";


const HomeOrLogin : React.FC = () => {
    /*If User is logged then, redirect to home, if not redirect to slides tutorial*/ 
    const storageService = new LocalStorageService();
    // Check if exits jwt in the phone
    storageService.getItem("jwt")
        .then((token )=>{
            /* If exists the jwt in the phone the user is logged */ 
            if(token){
                return <Redirect to="/Home" /> 
            }else{
                return <Redirect to="/slides" />
            }               
        })
        .catch((err)=>{
                console.log(err);
        })
};

export default HomeOrLogin;

Но оно показывает ошибку в компоненте

Type '() => void' is not assignable to type 'FC<{}>'.
  Type 'void' is not assignable to type 'ReactElement<any, any> | null'.

1 Ответ

1 голос
/ 30 апреля 2020

Рассматривали ли вы выполнение асинхронной петиции c в componentDidMount, а затем взамен того или иного экрана?

import React, { useState, useEffect } from 'react';

const HomeOrLogin : React.FC = () => {
    const [ redirect, setRedirect ] = useState(null);
    /*If User is logged then, redirect to home, if not redirect to slides tutorial*/ 

    useEffect(() => {
        const storageService = new LocalStorageService();
            // Check if exits jwt in the phone
            storageService.getItem("jwt")
                .then((token )=>{
                /* If exists the jwt in the phone the user is logged */ 
                    if(token){
                        setRedirect('/Home');
                    }              
                })
                .catch((err)=>{
                    console.log(err);
                })
    }, []);

    if (redirect) 
        return <Redirect to={redirect} />
    }
    return (
        <Redirect to="/slides" />
    )

 };

Таким образом, если есть токен, вы будете перенаправлены на Home, а в противном случае просто перенаправлен в /slides.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...