Redux -我已经改变了我的状态,在这之后我该怎么做呢?

Redux - I've changed my state how do I make things happen after this?

本文关键字:状态 在这之后 我该怎么做 我的 改变 Redux      更新时间:2023-09-26

我正在用redux编写我的登录系统,我觉得我应该从更简单的东西开始我的第一个redux:D

但:

减速器

function application (state = initialState, action) {
    switch (action.type) {
        case 'LOGIN_REQUEST':
            return Object.assign({}, state, { loggedIn: true, shouldRedirect: true });
        case 'LOGGED_IN':
            return Object.assign({}, state, { loggedIn: true, shouldRedirect: true });
        case 'LOGIN_FAILED':
            return Object.assign({}, state, { loggedIn: false, shouldRedirect: false, errorMessage: action.error.message })
    }
    return state
}
<<p> 操作/strong>
function receiveLogin(user) {
    return {
        type: LOGIN_SUCCESS,
        isFetching: false,
        isAuthenticated: true
    }
}
function loginError(message) {
    return {
        type: LOGIN_FAILURE,
        isFetching: false,
        isAuthenticated: false,
        message
    }
}
export function submitLogin (creds) {
    if(creds.email.length && creds.pw.length){
        return receiveLogin();
    }else{
        return loginError();
    }   
}

class SignIn extends React.Component {
    logIn = ( e ) => {
        console.info('as');
        e.preventDefault ();
        store.dispatch(authAction.submitLogin(this.state));
    };
    render = function () {
        return (
            <app-content class={loggedOut.home}>
                <Logo />
                <h1>Welcome to <br/> Kindred</h1>
                <h2>Please sign in to your account</h2>
                <form role="form" onSubmit={this.logIn}>
                    <input type="text" name="email" onChange={this.changed} component="input" placeholder="Enter email address"/>
                    <input type="password" name="pw" onChange={this.changed} component="input" placeholder="Password"/>
                    <button>Sign In</button>
                </form>
                <div className={loggedOut.extraDetails}>
                    <Link to="/signup">Don't have an account yet?</Link>
                    <Link to="/skip" className={loggedOut.extraDetailsRight}>Skip</Link>
                </div>
            </app-content>
        )
    }
};

表示LOGGED_IN状态改变。我究竟如何将我的状态与转发到另一个页面联系起来?我不能在我的减速器中加入任何这样的逻辑,这些必须是纯的。但是我需要将用户转发到另一个页面。我已经有了react-route,它上面有HOC来监视那些有或没有登录状态的人。但这只在渲染:/我不能把它添加到这个逻辑,因为这会触发每一个单独的页面查看

如果你的应用需要重定向,你可以重定向,而不是在成功时触发操作。重定向不是React组件或redux操作。如果有的话,它可以是异步操作创建器的一部分。

您可以通过订阅actions来监听您的store。商店。当您的商店分派操作时,subscribe(handlerFn)应该调用处理程序函数。在处理程序中,您可以检查状态并相应地做出反应,请原谅我的双关语。

您可以为路由创建redux中间件。因此,一旦您登录了,您就可以调度一个动作,让中间件拦截它,然后它开始行动并路由到下一个页面。因为你使用的是react-router,中间件可以是这样的:

    /**  Middleware  */
import { browserHistory } from 'react-router';
let navigate =  ( path) => {
  browserHistory.push(path);
};
export default store =>  next => action => {
  next(action);
  switch ( action.type ){
  case ActionTypes.NAV_TO_POST_LOGIN :
    navigate('/postLogin');
    break;
  }
}