首页 > 解决方案 > 登录成功反应redux时不重定向到HOC中传递的组件

问题描述

自从过去两天以来,我一直坚持表格日。当我使用 localhost:3000/app 时,应用程序作为组件传递给 HOC,因此我们看到登录页面,然后在成功时看到仪表板,但我不明白成功后何时成功失败并出现 错误:Invariant Violation:Maximum update depth超过。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。React 限制嵌套更新的数量以防止无限循环 请让我知道我的做法是正确的吗?

index.js // 路由写对了吗?

           <Provider store={store}>
                     <Switch>                                                  
                          <Route path="/" component={signIn}/>                                        
                          <Route handler={requireAuth(App)} name="App"/>
                     </Switch>  
               </Provider> 

Sigin.js

                  const mapStateToProps=(state)=>{
                    console.log("msp",state)
                    return{
                    isLoggedIn:state.signInReducer.isLoggedIn 
                    }
                  }

                  const mapDispatchToProps={
                    doLoginAction:doLoginAction
                  }

                  class SignInMain extends React.Component {
                    constructor(props){
                      super(props)
                      this.state={
                        userDetails:'',
                        errMsg:false
                      }
                    }

                    componentDidMount(){                    
                      if(this.props.isLoggedIn)
                      this.props.history.push('/app')                          
                    }                      

                    handleInput=(name,val)=>{                          
                      this.setState((prevState)=>{
                        {  const userDetails=prevState.userDetails
                          return{userDetails:{...userDetails,[name]:val}}
                        }
                      })                          
                    }

                    handleSubmit=()=>{                    
                         this.props.doLoginAction(this.state.userDetails)                                                
                    }

                    render(){
                      if(this.props.isLoggedIn) {
                        return this.props.isLoggedIn?<Redirect to="/app"/>:null
                      }

                    const { classes } = this.props;
                        return (
                          <main className={classes.main}>

                            <CssBaseline />
                            <Paper className={classes.paper}>
                            <Typography className={this.state.errMsg===true?classes.showErr:classes.hideErr}> Invalid Credentials</Typography>                   
                              <form className={classes.form} onSubmit={this.handleSubmit.bind(this)}>
                                <FormControl margin="normal" required fullWidth>
                                  <InputLabel htmlFor="email">Email Address</InputLabel>
                                  <Input id="email" name="email" autoComplete="email" autoFocus onChange={(e)=>this.handleInput('email',e.target.value)} />
                                </FormControl>
                                <FormControl margin="normal" required fullWidth>
                                  <InputLabel htmlFor="password">Password</InputLabel>
                                  <Input name="password" type="password" id="password" autoComplete="current-password"  onChange={(e)=>this.handleInput('password',e.target.value)} />
                                </FormControl>
                                <FormControlLabel
                                  control={<Checkbox value="remember" color="primary" />}
                                  label="Remember me"
                                />
                                <Button
                                  type="submit"
                                  fullWidth
                                  variant="contained"
                                  className={classes.submit}
                                >
                                  Sign in
                                </Button>
                              </form>
                            </Paper>
                          </main>
                        );
                    }
                  }

                  SignInMain.propTypes = {
                    classes: PropTypes.object.isRequired,
                  };

                  const SignIn=connect(mapStateToProps,mapDispatchToProps)(SignInMain)

                  export default withRouter(withStyles(styles)(SignIn));

需要Auth.js

                import React from 'react';
                import {withRouter} from 'react-router';

                export default function requireAuth(Component){
                        class AuthenticatedComponent extends React.Component{
                            componentDidMount(){
                                console.log(Component)
                                this.checkAuth()
                            }

                            checkAuth=()=>{                                   
                                if(!this.props.isLoggedIn){
                                    const location=this.props.location;
                                    const redirect=location.pathname+location.search;
                                    this.props.router.push(`/?redirect=${redirect}`);
                                }
                            }

                            render(){                                   
                                return this.props.isLoggedIn
                                ?<Component {...this.props}/>
                                :null;
                            }
                        }
                    return withRouter(AuthenticatedComponent);    
                }

控制台日志

                action LOGIN_ACTION @ 14:08:55.700

                prev state {signInReducer: {…}}

                action     {type: "LOGIN_ACTION", payload: {…}}

                next state {signInReducer: {…}}

                {email: "qsds@sdfs.com", password: "sdfsdfsdf"}


                http://localhost:3000/user

                 {status: "200", isLoggedIn: true, msg: "successfully LoggedIn"}

                 {status: "200", isLoggedIn: true, msg: "successfully LoggedIn"}

                 {signInReducer: {…}}
                signInReducer: {isLoggedIn: true}
                __proto__: Object
                 action LOGIN_SUCCESS @ 08:42:33.989
                prev state {signInReducer: {…}}
                action     {type: "LOGIN_SUCCESS", payload: {…}, @@redux-saga/SAGA_ACTION: true}payload: {status: "200", isLoggedIn: true, msg: "successfully LoggedIn"}type: "LOGIN_SUCCESS"@@redux-saga/SAGA_ACTION: true__proto__: Object
                error      Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

请让我知道我在做正确的事情,我知道我做错了,然后在渲染中重定向会导致问题,也不会进入那个状态。任何帮助表示赞赏。

如果我在登录组件的渲染功能中使用推送或重定向,我会收到以下错误我收到以下错误

不变违规:超过最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。React 限制了嵌套更新的数量以防止无限循环。

面临的问题

1.当 localhost:3000 然后它调用登录正确但成功时不会重定向到指定页面

  1. 当 localhost:3000/app 使用 HOC requireAuth 调用正确的 sigin 表单但即使在成功登录后也不会调用 RequireAuth 渲染,以便我们进入组件

任何人都可以请让我知道我要去哪里错了吗?请帮忙

标签: reactjsreduxreact-reduxreact-routerredux-saga

解决方案


推荐阅读