小编Jus*_*tin的帖子

React-Redux如何在重定向之前防止页面呈现

我正在处理一个个人项目,无法检查用户是否已登录,因此当他们尝试转到/ login时,它将把他们重定向到主页。目前,我的代码执行以下操作:

  1. 定义了我自己的路线组件
  2. 调用checkIfSignedIn时,它将分派将isLoggedIn状态设置为True或False的操作。
  3. AuthenticatedRouter组件检查商店的isLoggedIn状态是true还是false,并将呈现该组件或重定向到主页。
  4. 此方法有效,但是问题在于isLoggedIn最初为false,因此如果登录,则登录表单会显示一秒钟,然后在isLoggedIn变为true后重定向。

我无法弄清楚如何使用默认状态渲染组件,然后由于状态更改而突然重定向,从而解决该问题。谢谢

  • 我正在为用户帐户使用Firebase。

Routes.js

const Routes = (props) => {
    props.checkIfSignedIn();
    return(
        <Router>
            <Switch>
                <Route exact path='/' component={App}/>
                <AuthorizedRoute path="/signup" component={SignUp}/>
                <AuthorizedRoute path="/signin" component={SignIn}/>
                <Route component={InvalidPage}/>
            </Switch>
        </Router>
    );
};

const mapDispatchToProps = (dispatch) => {
    return{
        checkIfSignedIn: () => dispatch(checkIfSignedIn())
    };
};

export default connect(null, mapDispatchToProps)(Routes);
Run Code Online (Sandbox Code Playgroud)

AuthorizedRoute.js

class AuthorizedRoute extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            isLoggedIn: false
        };
    };

    render(){
        const { component: Component, ...rest } = this.props;
        return(
            <Route {...rest} render={props => …
Run Code Online (Sandbox Code Playgroud)

reactjs react-router redux react-redux

5
推荐指数
1
解决办法
1597
查看次数

标签 统计

react-redux ×1

react-router ×1

reactjs ×1

redux ×1