【问题标题】:How to return diferent pages in React functional component如何在 React 功能组件中返回不同的页面
【发布时间】:2020-08-14 22:29:22
【问题描述】:

我正在创建一个反应应用程序,当我的应用程序启动时,我想知道用户是否登录以将他发送到主页。 当我的应用启动“/”路由时加载此页面

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'.

【问题讨论】:

    标签: reactjs ionic-framework react-hooks react-functional-component


    【解决方案1】:

    您是否考虑过在 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。

    【讨论】:

    • 嗨,我是 react 新手,Cannot find name 'componentDidMount'. 也许是我用离子反应构建的?
    • 对不起兄弟,您使用的是功能组件,我会编辑它
    • 没问题的朋友!
    猜你喜欢
    • 1970-01-01
    • 2020-02-03
    • 2017-04-24
    • 1970-01-01
    • 2021-06-09
    • 2022-01-03
    • 2021-12-23
    • 2018-10-12
    • 2011-03-06
    相关资源
    最近更新 更多