【问题标题】:preventing user from being redirected to homepage when refreshing and staying on the same page React JS防止用户在刷新并停留在同一页面时被重定向到主页 React JS
【发布时间】:2021-09-01 14:03:16
【问题描述】:

这是我的代码,我通过 props 将身份验证状态和令牌传递给其他组件: 问题是当我刷新页面时,它会将我重定向到主页。

这是我的代码:

class App extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            account: {
                email: "",
                password: ""
            },
           
            token: "",
            auth: false
        };

    }
    
    
    confirm = async (email) => {
            let result;
            let stateAccount;
            let authToken;
            let myCookie;
            let storedCookie;

            try {
                result = await axios.post(`http://localhost:5000/abc/dosomething`, {email},{withCredentials: true});

                stateAccount = this.state.account
                stateAccount.email = email;
                this.setState({stateAccount});


                console.log(result);

                if (this.state.account.email === result.data.Email && this.state.account.password === result.data.OTPCode) {
                    authToken = result.headers.accesstoken;
                    this.setState({token: authToken});

                    myCookie = this.addCookies();
                    myCookie = myCookie.split('=');
                    storedCookie = myCookie[1].trim();

                } else {
                    console.log(`Invalid Login!`);
                    
                }


                let history = this.props.history;



                if(this.state.token === storedCookie){
                    console.log("Successful Login!");
                    console.log(`found cookie: ${storedCookie}`);
                    this.setState({auth: true});
                    history.push({pathname: "/some-endpoint/abc", state: {stateAccount}});

                }else{
                    this.setState({errorMessage: "Invalid Login!"});
                }



            }catch(error){ //set this to Permission Denied in production
                console.log(`${error.data}`});
            }
        }
    
    notLoggedInhomePage = () =>{

        if(!this.state.auth) {
            return (
                <form onSubmit={this.handleSubmit}>
                        <label>Email Address</Form.Label>
                        <input type="text" value={this.state.account.email} onChange={this.handleChange} name="email"/>
                    
                        <label>Password</Form.Label>
                        <input type="password" value={this.state.account.password} onChange={this.handleChange} placeholder="Enter One Time Password" name="password"/>
                    

                    <button type="submit" onClick={() => this.someFunction(String(this.state.account.email))}>Do Something</button>
                    <button type="submit" onClick={() => this.someOtherFunction()}>Do something else</button>
                </form>
            );
        }else{
            return(<Redirect to="/logged-in-page/signed-in" />);
        }
}


      render(){

        return(
            <Router>
                {this.notLoggedInhomePage()}
                <Switch>
                    <Route path="/list" exact component={AComponent} auth={this.state.auth} account={this.state.account} token={this.state.token}  />
                </Switch>
            </Router>
        );
    }

我知道状态是一个临时内存,但我想做的是,当我刷新页面时,我希望用户停留在刷新之前他们所在的页面上。然而发生的情况是它们被重定向回主页(即登录屏幕),因为 this.state.auth 将等于 false,如上面在 notLoggedInhomePage 中所示。

解决上述问题的最佳解决方案是什么?

【问题讨论】:

  • State.authenticated 不在您的初始状态,因此 undefined 不严格等于 false
  • if(this.state.authenticated === false),应该是:if(!this.state.auth)

标签: javascript reactjs react-redux react-router


【解决方案1】:

我通过从 notLoggedInhomePage = () => 方法中删除 else 块解决了上述问题。

我删除了:

else{
        return(<Redirect to="/logged-in-page/signed-in" />);
}

【讨论】:

    【解决方案2】:

    在我看来,最好的解决方案与改变初始状态有关。 例如,您可以像这样读取身份验证令牌表单 cookie:

    const token = document.cookie
      .split('; ')
      .find(row => row.startsWith('AUTH'))
      .split('=')[1]
    const isValidToken = !!token;
    
    this.state = {
      token: token,
      auth: isValidToken
    }

    当然,这是伪代码,所以你应该注意令牌验证。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-03
      • 1970-01-01
      • 2016-05-29
      • 2021-07-04
      • 2016-01-15
      • 1970-01-01
      相关资源
      最近更新 更多