我们能在redux-saga中进行重定向吗?

8
我有一个登录页面,使用 HOC 传递组件,在成功登录后必须渲染。如果在 sigin-in 的 render 中检查 isLoggedIn 并重定向,则会出现错误:
err: 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。
           try{//call api
                //put login success
              <Redirect to="/app"/>        
            }

index.js

          const AuthProfile=requireAuth(App);

           In reactdom
             <Route render={(props)=><AuthProfile  {...props}/>} path="/app"/>  


          import React, { PropTypes } from 'react';  
          import { connect } from 'react-redux';  
          import { push } from 'react-router-redux';
          import { bindActionCreators } from 'redux';

          export default function (ComposedComponent) {  
            class Authenticate extends React.Component {


              componentDidMount() {
                console.log("12ra")
                this._checkAndRedirect();
              }

              componentDidUpdate() {
                this._checkAndRedirect();
              }

              _checkAndRedirect() {
                const { isLoggedIn, redirect } = this.props;

                if (!isLoggedIn) {
                  redirect();
                }
              }

              render() {
                console.log("28ra")
                return (
                  <div>
                    { this.props.isLoggedIn ? <ComposedComponent {...this.props} /> : null }
                  </div>
                );
              }
            }

            const mapStateToProps = (state) => {
              return {
                isLoggedIn:state.signInReducer.isLoggedIn
              };
            };

            const mapDispatchToProps = dispatch => bindActionCreators({
              redirect: () => push('/')
            }, dispatch)

            //Authenticate.propTypes = propTypes

            return connect(
              mapStateToProps, 
              mapDispatchToProps
            )(Authenticate);
          }       

高阶组件(HOC)组件是否正确或者我漏掉了什么?

在saga中重定向是一个好的实践吗?

请问有谁知道,在成功后如何访问应用程序组件,我卡在那里了,请帮忙谢谢。

更新

saga.js

       yield put({type:LOGIN_SUCCESS,payload:data})
        yield put(push('/app'))

index.js

我需要为页面1和页面2提供示例:

        <AuthRoute
      exact
      path="/"
      component={Page1}
      redirectTo="/login"
      authenticated={this.props.isLoggegIn}
    />

     <AuthRoute
      exact
      path="/"
      component={Page2}
      redirectTo="/login"
      authenticated={this.props.isLoggegIn}
    />
2个回答

8
以下是从saga导航的方法:
import { push } from 'react-router-redux';
...
// after API call & validate user
yield put(push('/app'));

index.js

 <Route strict exact path='/app' component={App}>
 <AuthRoute
          exact
          path="/"
          component={Yourcomponent}
          redirectTo="/login"
          authenticated={hasAccessToken()}
        />

我更新了我的回答,如果你需要身份验证(在这里我考虑了基于令牌的身份验证),你可以使用AuthRoute - iamrajshah
请检查saga.js中更新的代码是否是我们编写的方式。另一件事是我没有访问令牌,authroute是内置库吗?我很困惑{Yourcomponent}可以是“app”,或者app必须有不同的路由? - withFlow
是的,你写的代码是正确的,它可以作为一个单独的操作,调用该操作也是可以的。如果你没有访问令牌,那么可以删除该部分或者添加自己的机制来验证用户是否已登录,并检查它而不是使用 hasAccessToken()。 - iamrajshah
请检查一下,我已经更新了代码、saga和索引。 - withFlow
FYI- react-router-redux已被弃用。他们建议使用connected-react-router。代码与上述相同。https://www.npmjs.com/package/connected-react-router。https://github.com/reactjs/react-router-redux - sirclesam
显示剩余4条评论

7

我将告诉你最好的、最简单的方法,让你可以在应用程序的任何部分(例如在redux中内部和外部)进行重定向。

步骤:1 创建 history.js 文件。

import { createBrowserHistory } from 'history';

export default createBrowserHistory();

第二步:将它导入App.js文件中(或者是你的应用程序路由所在的位置)。

import React from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import * as ROUTES from '../../constants/Routes';
import history from './history';

const App = () => {
    return (<Router history={history}>
        <div className='App'>
            <Switch>
                <Route exact path={ROUTES.NOTIFICATIONS} component={Notification} />
                <Route exacr path={ROUTES.USER_PROFILE} component={UserProfile} />
                <Route exact path={ROUTES.SIGN_IN} component={SignInPage} />
                <Route exact path={ROUTES.SIGN_UP} component={SignUpPage} />
                <Route path='*' component={SignInPage} />
            </Switch>
        </div>
    </Router>
    );
};

export default App;

步骤 3:在Saga文件中导入history。

import { push } from 'react-router-redux';
import { Auth } from "../service/api/Auth";
import history from '../containers/App/history';
import * as ACTION from '../constants/ActionType';
import { put, takeLatest, call } from "redux-saga/effects";
import { userLoginSuccess, userLoginFailed } from "../actions/auth";

export function* userLogin(loginData) {

  const payLoad = loginData.payload;
  try {
    const loginUserData = yield call(Auth.userLoginApiCall, payLoad);
    yield put(userLoginSuccess(TOKEN));
    history.push('/posts'); //  Redirect to Post Page
  } catch (err) {
    yield put(push(userLoginFailed()))
  }
}

export default function* userLoginRequest() {

  yield takeLatest(ACTION.USER_LOGIN_REQUEST, userLogin);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接