首页 > 解决方案 > 如何从 redux 中的动作事件重定向

问题描述

我想在触发操作后重定向客户端。我听说过react-redux-router,但不确定如何在操作函数中正确实现它。

我关注了一点

https://stackoverflow.com/a/42985875/10865515

但是,当我提交经过验证的表单时,它不会重定向或刷新。

Actions.js

 import { auth as firebaseAuth } from '../firebaseConfig'
 import { push,  browserHistory } from 'react-router-redux';


 export const signUp = (user) => { return (dispatch) => {
  firebaseAuth.createUserWithEmailAndPassword(user.email, user.password)
    .then(() => {
        dispatch({ type: 'SIGNUP_SUCCESS',
        payload: (action, state, res) => {
            return res.json().then(json => {
              browserHistory.push('/');
              return json;
            });
          },
    });
    }).catch((err) => {
        dispatch({ type: 'SIGNUP_ERROR', err});
    });
  }  
}

减速器.js

const initialState = {
  emailSignUp: '',
  passwordSignUp: '',
  authError: null

}

export default (state = initialState, action) => {
  switch (action.type) {
    case 'SIGNUP_SUCCESS':      
        return ({
            ...state,
            authError: null
        })

    case 'SIGNUP_ERROR':
        console.log('signup error')
        return ({
            ...state,
            authError: action.err.message
        })
    default:
        return state
 }
} 

注册.js

// ...
handleSubmit(event) {
    event.preventDefault();

    const {formData, errors} = this.state;
    const {email, password} = formData;

    const myError = this.props.authError;
    const creds = {
        email,
        password
    }
    const register = this.props.signUp(creds);
    if (register) {
        console.log(creds);

    }
}

标签: javascriptreactjsreact-redux

解决方案


您应该实现react-router-dom允许您访问history对象以进行导航的库。

在触发动作创建者的组件中:

import { withRouter } from "react-router-dom"

然后在代码的底部,您调用连接:

export default connect(mapStateToProps, mapDispatchToProps)(withRouter(myComponent))

现在您可以设置您的动作创建者以将历史记录作为参数。

您的操作文件:

const signUp = (creds, history) => {
//do some logic then go home
   history.push("/")
}

因此,在您调用动作创建者的事件处理程序中,传入历史记录:

handleSubmit(event) {
    event.preventDefault();

    this.props.signUp(creds, this.props.history);
    if (register) {
        console.log(creds);
    }
}

推荐阅读