当前位置: 首页 > 知识库问答 >
问题:

未登录时重定向使用

东郭鹤龄
2023-03-14

我正在尝试重定向用户,如果他/她还没有登录。我正在使用下面的狙击手来做那件事。

if(!this.props.isAuthenticated){
    this.nextPath('/account/login')
}

我也附上了完整的代码。请帮助我调试此问题。

import React, { Component, Suspense } from 'react'
import { Layout, Menu } from 'antd';
import {TagFilled, SettingFilled , FileAddOutlined, DeleteFilled, LogoutOutlined } from '@ant-design/icons';
import { renderRoutes } from 'react-router-config';
import { loadLabels, deleteLabel} from '../../Store/Action/label'
import { logout } from '../../Store/Action/auth'
import { connect } from 'react-redux';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import Button from '@material-ui/core/Button';
import AddLabel from './Components/AddLabel'
import SideBar from './Components/SideBar'
import Avatar from '@material-ui/core/Avatar';
import {Dropdown} from 'react-bootstrap'
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import { Row, Col, ListGroup } from 'react-bootstrap';
import Typography from '@material-ui/core/Typography';
import Divider from '@material-ui/core/Divider';
import ListSubheader from '@material-ui/core/ListSubheader';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import { Redirect } from 'react-router-dom';
const { Header, Content, Footer, Sider } = Layout;


export  class HomePage extends Component {
    //Constructor
    constructor(){
        super()
        this.state = {
            collapsed: false,
            addLabelVisible: false,
            isHovered: {},
            anchorEl: null, 
            setAnchorEl: null
        };
        this.addLabelToggle = this.addLabelToggle.bind(this)
        this.handleMouseEnter = this.handleMouseEnter.bind(this);
        this.handleMouseLeave = this.handleMouseLeave.bind(this);
        this.handlelogOut = this.handlelogOut.bind(this);
        this.fetchData = this.fetchData.bind(this);
    }
    
    //Collapse the Sidebar
    onCollapse = collapsed => {
        this.setState({ collapsed });
    };

    //Toogle  Add Label Dialog
    addLabelToggle(addLabelVisible) {
        this.setState({ addLabelVisible });
    }

    //Fetch All labels from the API
    componentDidMount(){
    console.log('problem here 1')
        this.props.loadLabels()
    }

    //API CAll
    fetchData(){
        this.props.loadLabels()
    }

    //Called Whenever new Label is Added
    componentDidUpdate(prevProps) {
            if(typeof(prevProps.labels) === 'undefined' ) {
                this.fetchData()
            }
            else if(prevProps.labels === this.props.labels){
                this.fetchData()
            }else{
    
            }
      }

    //Hover
    handleMouseEnter = index => {
    this.setState(prevState => {
        return { isHovered: { ...prevState.isHovered, [index]: true } };
    });
    };
    
    //Hover
    handleMouseLeave = index => {
    this.setState(prevState => {
        return { isHovered: { ...prevState.isHovered, [index]: false } };
    });
    };

    //Delete a Label
    handleLabelDelete(id){
        const data = {
            id: id,
            img: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png'
        }
    this.props.deleteLabel(data)
    }

    handleClick = (event) => {
        this.setState({
            anchorEl: event.currentTarget
        })
    };
    
    handleClose = () => {
        this.setState({
            anchorEl: null
        })
    };

    handlelogOut = (e) =>{
        console.log('logout')
        this.props.logout()
    }

    
    nextPath(path) {
        this.props.history.push(path);
    }
  
  
    render() {
        const open = Boolean(this.anchorEl);
        const id = open ? 'simple-popover' : undefined;
        const { arr, isHovered } = this.state;
        console.log(this.props.request)
        if(!this.props.isAuthenticated){
            this.nextPath('/account/login')
        }
        return (
          <Layout style={{ minHeight: '100vh' }}>

            {/* Navbar */}
            <Header className="header" style={{ height: '60px', backgroundColor: '#1a243a' }}>
                <div style={{ width: '120px', height: '31px', float: 'left', margin: '16px 28px 16px 0' }}>
                    <h2 style={{ color: 'white' }}>Nexdo</h2>
                </div>
                <div style={{ float: 'right' }}>
                    <Dropdown>
                        <Dropdown.Toggle style={{ backgroundColor: 'transparent', borderColor: 'transparent' }} id="dropdown-basic">
                            <Avatar>{this.props.user?this.props.user.first_name.slice(0,1):""}</Avatar>
                        </Dropdown.Toggle>
                        <Dropdown.Menu>
                            <Card style={{ background: '#ffffff',  boxShadow: 'none', width: '280px' }}>
                                <CardContent>
                                    <Row>
                                        <Col xs={9}>
                                            <Typography style={{  alignContent: 'right', justifyContent: 'right', display: 'flex'  }} variant="h6" noWrap>
                                                {this.props.user?this.props.user.first_name:""} {this.props.user?this.props.user.last_name:""}
                                            </Typography> 
                                            <Typography style={{ color: '#333333',  fontSize: '11px' , alignContent: 'right', justifyContent: 'right', display: 'flex'  }} variant="h6" noWrap>
                                                {this.props.user?this.props.user.email:""}
                                            </Typography> 
                                        </Col>
                                        <Col xs={3}>
                                            <Avatar>{this.props.user?this.props.user.first_name.slice(0,1):""}</Avatar>
                                        </Col>
                                    </Row>
                                </CardContent>
                                <Divider />
                                <List
                                    component="nav"
                                    aria-labelledby="nested-list-subheader"
                                    subheader={
                                        <ListSubheader component="div" id="nested-list-subheader">
                                        Actions
                                        </ListSubheader>
                                    }
                                    >
                                    <ListItem button>
                                        <ListItemIcon>
                                        <SettingFilled />
                                        </ListItemIcon>
                                        <ListItemText primary="Profile" />
                                    </ListItem>
                                    <a onClick={this.handlelogOut}>
                                    <ListItem  button>
                                        <ListItemIcon>
                                        <LogoutOutlined />
                                        </ListItemIcon>
                                        <ListItemText primary="Logout" />
                                    </ListItem>
                                    </a>
                                </List>
                            </Card>
                        </Dropdown.Menu>
                    </Dropdown>
                </div>
            </Header>

            {/* SideBar and Content */}
            <Layout className="site-layout">
                <SideBar labelData = {this.props.labels} addLabelToggle = {this.addLabelToggle}/>
                {/* Content which will be loaded dynamically */}
                <Content style={{ margin: '0 16px' }}>
                    <main  style={{ backgroundColor: "#fafafa", minHeight: '-webkit-fill-available' }} >
                        <Suspense fallback={<div>Loading...</div>}>
                            {renderRoutes(this.props.route.routes,)}
                        </Suspense> 
                    </main> 
                </Content>
            </Layout>

            {/* Footer */}
            <Footer style={{ textAlign: 'center' }}>Joan Louji ©2020 Created by Joan Louji</Footer>

            {/* Add Label Dialog Box */}
            <Dialog scroll="paper"  open={this.state.addLabelVisible}  onClose={()=>this.addLabelToggle(false)} aria-labelledby="scroll-dialog-title" aria-describedby="scroll-dialog-description">
                <DialogTitle id="form-dialog-title"><b>Labels</b></DialogTitle>
                <DialogContent>
                    <div style={{  height: "400px", width: "300px" }}>
                        {/* Display the Add Label Box */}
                        <AddLabel editClassName="form-control" value="Create a new Label" />
                        {this.props.labels?(this.props.labels.length==0?
                            <div style={{ margin: "0 auto", fontSize: '60px' ,display: 'flex' ,justifyContent: 'center', alignContent: 'center', alignItems: 'center', height: '100%', color: '#e0ebff'}}>
                                <div className="row">
                                    <div className="col-12"> 
                                        <FileAddOutlined  style={{ margin: "0 auto", fontSize: '60px' ,display: 'flex' ,justifyContent: 'center', alignContent: 'center', alignItems: 'center', height: '100%', width: '100%' ,color: '#e0ebff'}}/>{"\n"}
                                    </div>
                                    <div className="col-12">
                                        <h3 style={{ margin: "0 auto", fontSize: '20px' ,display: 'flex' ,justifyContent: 'center', alignContent: 'center', alignItems: 'center', height: '100%', width: '100%' ,color: '#e0ebff', marginTop: '20px'}}>Label Not Found</h3>
                                    </div>
                                </div>
                            </div>
                        :
                        ""
                        ):"sd"}
                        {/* Render All the Labels in the Dialog Box */}
                        {this.props.labels?this.props.labels.map((data,index)=>{
                        return(
                                <div style={{ marginTop: '20px', }} >
                                    <div key={data.name}>
                                        <div className="row">
                                            <div className="col-1" onMouseEnter={()=>this.handleMouseEnter(index)} onMouseLeave={()=>this.handleMouseLeave(index)}>
                                                {this.state.isHovered[index]?
                                                    <DeleteFilled style={{ fontSize: 17, color: 'grey', cursor: 'pointer' }} onClick={(e)=>this.handleLabelDelete(data._id)}/>
                                                :
                                                    <TagFilled style={{ fontSize: 17, color: 'grey' }}/>
                                                }
                                            </div>
                                            <div className="col-9">
                                                {data.name}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            )
                        }):
                        <div>
                            <FileAddOutlined />
                        </div>
                        }
                    </div>
                </DialogContent>
                <DialogActions>
                    <Button onClick={(e)=>{
                        this.addLabelToggle(false)
                    }}>Done</Button>
                </DialogActions>
            </Dialog>
          </Layout>
        );
    }
}

//mapStateToProps
const mapStateToProps = (state) => ({
    isLoading: state.labels.isLoading,
    user: state.auth.user,
    labels: state.labels.labels,
});

export default connect(mapStateToProps, {loadLabels, deleteLabel, logout})(HomePage)

共有1个答案

公西修文
2023-03-14

从错误中可以清楚地看出,您在ComponentDidUpdate中提到的“if”条件正在重复调用setState。这就是为什么react框架限制。请参考组件Did更新

 类似资料:
  • 问题内容: 我的应用看起来像: 如果用户访问/ game下的页面并没有登录,我想将他们重定向到登录页面。 如何在所有路由器中做到优雅? 问题答案: 基本思想是使用自定义组件(在下面的示例中为PrivateRoute)包装需要身份验证的路由。PrivateRoute将使用某种逻辑来确定用户是否已通过身份验证,然后确定是否通过身份验证。允许请求的路由呈现或重定向到登录页面。 在react-router

  • 我的应用程序看起来像: 如果用户访问 /game下的页面并且没有登录,我想将他们重定向到登录页面。 如何在所有路由器中以优雅的方式进行?

  • 我想在登录到我的索引页面(index.jsp)后进行重定向,实际上我的登录可以正常工作,但ajax支持缺少重定向。 她是我的登录名。jsp 这是我的登录 我的struts配置文件: 对于DAO部分是: 公共字符串验证(字符串用户名,字符串userpass)抛出SQLException,Exception{ 谢谢你的帮助。

  • 我是新的编码,请我需要在这个特定的功能的帮助,我将非常感激,如果有人可以帮助。 我在一个android studio项目上工作,在我的活动(假设活动A)我想放置一个按钮,当点击它将打开假设活动B。 我已经能够设置onclick功能,并打算在按钮单击上打开活动B。

  • 我在laravel中遇到了一个用户登录的问题,我可以正确地登录用户,但是问题是,在用户登录后,他被重定向到login POST方法,而不是home,我已经将

  • 安全性:编码器:AppBundle\Entity\Usuario:算法:bcrypt#https://symfony.com/doc/current/security.html#b-配置如何加载用户提供程序:db\U提供程序:实体:类:AppBundle:Usuario

  • 我正在将DNN应用程序从07.00.02升级到07.03.04并在安装后将所有门户重定向到登录页面。所有门户都配置有一个登陆页面,该页面被配置为允许“所有用户”角色视图访问。还有人在升级后遇到过这个问题吗? 2015-02-05 05:45:01 127.0.0.1 GET/-80-127.0.0.1 Mozilla/5.0+(Windows+NT+6.3;+WOW64)+AppleWebKit/

  • 记录器文件中的日志- org.springframework.Security.Access.event.loggerlistener-安全授权失败,原因是:org.springframework.Security.Access.accessdeniedexception:访问被拒绝;通过身份验证的主体:org.springframework.security.authentication.ano