【问题标题】:Axios-Redux in React to an Express endpoint-both .then and .catch triggeredReact 中的 Axios-Redux 对 Express 端点 - .then 和 .catch 都触发
【发布时间】:2017-12-25 15:08:21
【问题描述】:

我正在使用 Redux 表单向 Express 端点发送 POST 调用。端点应该返回成功保存的对象,否则返回错误。

端点成功保存发布的数据并返回 JSON。但是 Redux 操作中的 Axios 会同时提取 .then 和 .catch 触发器——在以下操作中,它会记录以下内容:

successful response:  { …}
failure response:  undefined

我做错了什么?

我的 Axios 操作:

export function addPlot(props) {
    const user = JSON.parse(localStorage.getItem('user'));
    return function(dispatch) {
        axios
            .post(
                `${ROOT_URL}/plots`,
                {
                    props
                },
                { headers: { authorization: user.token } }
            )
            .then(response => {
                console.log('successful response: ', response.data);
                const plotModal = document.getElementById('plotModal');
                plotModal.modal('dispose');
                dispatch({ type: PLOT_ADDED, payload: response.data });
                dispatch({ type: ADDING_PLOT, payload: false });
                dispatch({
                    type: NEW_PLOT_GEOJSON,
                    payload: ''
                });
            })
            .catch(response => {
                console.log('failure response: ', response.data);
                dispatch(authError(PLOT_ADD_FAILURE, 'Failed to add plot'));
            });
    }

我的端点:

exports.newPlot = async (req, res, next) => {
    console.log(JSON.stringify(req.body.props));
    let company;
    if (req.user.companyCode !== 'Trellis') {
        company = req.user.companyCode;
    } else {
        company = req.body.props.company;
    }
    const {
        name,
        feature,
        growerPhone,
        plotCode,
        rootStock,
        region,
        variety,
        grower,
        planted
    } = req.body.props;
    const plot = new Plot({
        name,
        grower,
        variety,
        planted,
        region,
        rootStock,
        plotCode,
        growerPhone,
        feature,
        company
    });
    try {
        const newPlot = await plot.save();
        res.json(newPlot);
    } catch (e) {
        console.log("couldn't save new plot", JSON.stringify(e));
        return res.status(422).send({ error: { message: e, resend: true } });
    }
};

【问题讨论】:

    标签: reactjs express redux axios


    【解决方案1】:

    您可以使用redux-thunk 中间件来管理异步操作。

    我看到的问题是你没有调度 axios 动作,你必须调用dispatch(this.props.addPlot(props))才能在 redux store 中做一些事情。

    【讨论】:

    • 对不起,你什么意思?
    • 您没有发送操作(或重击)addPlot。在调用的那一刻,在你的反应组件中,你必须用this.props.dispatch 包装它。希望它有效。
    猜你喜欢
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    相关资源
    最近更新 更多