【问题标题】:How can I redirect to a route depending on the outcome of an action如何根据操作的结果重定向到路线
【发布时间】:2021-07-31 10:16:30
【问题描述】:

我正在使用 redux 构建一个反应应用程序。当用户提交表单时,有两种可能的结果:错误或成功。

这是动作创建者:

export const createSomething = (data) => {
return (dispatch, getState, { getFirebase, getFirestore }) => {
    const firestore = getFirestore();

    firestore.collection('data_s').add( {
        ...data,
    }).then((dts) =>{
        dispatch({
            type : 'CREATED_SUCCESS', dts
        });
    }).catch((err) => {
        dispatch({
            type : 'CREATE_ERROR', err
        });
    })
}

};

和减速器:

const createSomethingReducer = (state = initState, action) => {
    switch (action.type) {
        case 'CREATED_SUCCESS' : 
            console.log('created', action.data);
            return state;

        case 'CREATE_ERROR' :
            console.log('create error', action.err);
            return state;

        default : 
            return state
    }
}

提交是这样完成的

handleSubmit = (e) => {
    e.preventDefault();
    this.props.createEmployee(this.state)
}

如果表单提交成功,我将如何定向到“/success”,如果表单没有通过,我将如何定向到“/error”?

我尝试过使用

this.props.history.push('/app/dashboard')

但是无论结果如何,这都会重定向。请帮忙。

谢谢

【问题讨论】:

    标签: reactjs redux react-router-dom


    【解决方案1】:

    您可以让 createEmployee 函数中的 .then 块返回,以便承诺链继续,然后在 handleSubmit 函数调用中

    .then(() => this.props.history.push('/success'))
    

    您可以通过在 createEmployee 函数的 catch 中抛出错误,然后在 handleSubmit 函数调用中继续 catch 来对 catch 块执行相同的操作

    .catch(err => this.props.history.push('/error'))
    

    最终的函数应该是这样的

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.createEmployee(this.state)
       .then(() => this.props.history.push('/success'))
       .catch(err => this.props.history.push('/error'))
    }
    

    【讨论】:

    • 当我添加一个 .then 时,它给了我一个无法读取未定义错误的属性。
    • 您是否在原始承诺链中添加了return。然后在 createEmployee 中?
    • 是的,我做到了。新的是 return ([ dispatch({ type : 'CREATED_SUCCESS', dts, }) ])
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 2015-08-12
    • 2020-12-09
    相关资源
    最近更新 更多