2016-12-04 87 views
1

我很努力地理解哪裏是處理成功提交和導航到下一頁的最佳實踐。Redux表單導航提交成功

我正在登錄表單上:

class LogInComponent extends Component { 

    render() { 
     const {dispatch} = this.props; 
     const {loginError, handleSubmit, pristine, reset, submitting} = this.props; 

     return (
      <form onSubmit={handleSubmit((values) => dispatch(login(values))) }> 
       <Field name="username" type="text" component={renderField} label="Username" /> 
       <Field name="password" type="password" component={renderField} label="Password" /> 
       {loginError && <strong>{loginError}</strong>} 
       <div> 
        <button type="submit" disabled={submitting}>Log In</button> 
        <button type="button" disabled={pristine || submitting} onClick={reset}>Clear Values</button> 
       </div> 
      </form> 
     ) 
    } 

和動作:

export function login(values) { 
    const email = values.username; 
    const password = values.password; 
    return dispatch => { 
     dispatch(loginSubmit()); 
     firebaseAuth.signInWithEmailAndPassword(email, password).then(function(user) { 
      dispatch(signInSuccess(user)); 
     }).catch(function(error) { 
      dispatch(signInError(error)); 
     }); 
    }; 
} 

export function loginSubmit() { 
    return { 
     type: SIGN_IN_SUBMIT 
    }; 
} 

export function signInError(error) { 
    return { 
     type: SIGN_IN_ERROR, 
     payload: error.message 
    }; 
} 

export function signInSuccess(user) { 
    return { 
     type: SIGN_IN_SUCCESS, 
     payload: user 
    }; 
} 

如果響應是成功的,我想導航到下一個頁面。但導航應該在哪裏?不是從減速器或行動,所以只從組件,但行動不會回覆設計。 我錯過了什麼?

+0

到目前爲止,我使用'browserHistory'從裏面'反應,router'我在生產模式下操作沒有問題。所以如果你在'dispatch(signInSuccess(user))之下放置'broswerHistory.push(yourLink)'''它應該就好了。 –

回答

0

創建一個組合函數來耦合您的登錄代碼和導航邏輯,以及在表單提交時起作用的dispatch

修改操作文件如下:

import { browserHistory } from './react-router'; 

// no export needed, this is a @private function 
function login(values) { 
    const email = values.username; 
    const password = values.password; 
    return dispatch => { 
     dispatch(loginSubmit()); 
     return firebaseAuth.signInWithEmailAndPassword(email, password) 
     .then((user) => dispatch(signInSuccess(user))) 
     .catch((error) => dispatch(signInError(error))); 
    }; 
} 

export function loginAndRedirect(loginParams) { 
    return dispatch => dispatch(login(loginParams)) 
    .then(() => browserHistory.push('/success/path')) 
    .catch(() => browserHistory.push('/failure/path')); 
} 

// ... other actions 

現在我們的組件,我們將做到這一點:

<form onSubmit={handleSubmit((values) => dispatch(loginAndRedirect(values))) }>