【问题标题】:How to make a post request with axios (React Redux Hook)?如何使用 axios (React Redux Hook) 发出 post 请求?
【发布时间】:2021-04-04 11:12:57
【问题描述】:

我想用 axios (React Redux Hook) 设置一个 post 请求。

如何在表单中使用我的操作? 有教程吗?

当然知道表单是带有 onSubmit 的基本表单。

这是我的 redux 操作:

export const createUserSuccess = (data) => {
    return {
        type: types.ADD_USERS_SUCCESS,
        payload: data,
    }
}

export const createUserError = (data) => {
    return {
        type: types.ADD_USERS_ERROR,
        payload: data
    }
}

export const createUser = (user) => {
    const userData = {
        id: [0],
        firstName: user.firstName,
        lastName: user.lastName,
        password: user.password,
        emailAddress: user.emailAddress,
    }
    return (dispatch) => {
        return axios.post('/users', userData, {headers: authHeader()})
            .then(response => {
                const id = response.data.id
                axios.get(`/users/${id}`, {headers: authHeader()})
                    .then(response => {
                        const data = response.data
                        dispatch(createUserSuccess(data))
                        history.push('/')
                    })
                    .catch(error => {
                        debugger
                        const errorPayload = {}
                        console.log(errorPayload, error)

                        errorPayload['message'] = error.response.data['hydra:description'];
                        errorPayload['error'] = error.response.status
                        dispatch(createUserError(errorPayload))
                    })
            })
            .catch(error => {
                const errorPayload = {}

                errorPayload['message'] = error.response.data['detail'];
                errorPayload['error'] = error.response.status
                dispatch(createUserError(errorPayload))
                console.log(error.response.data)
            })
    }
}

【问题讨论】:

    标签: reactjs redux axios


    【解决方案1】:

    使用 Axios 创建 post 请求非常简单。

    https://github.com/axios/axios#axios-api

    为了与 redux 集成,我建议使用 Redux Toolkit。它带有 Redux Thunk 作为中间件,并提供回调来处理 redux 存储中的各种数据操作。

    可在此处找到指南 - Redux Toolkit

    【讨论】:

      猜你喜欢
      • 2021-03-01
      • 2019-04-05
      • 2020-11-07
      • 2022-11-02
      • 2017-11-30
      • 2019-11-24
      • 2020-03-01
      • 2020-09-17
      • 1970-01-01
      相关资源
      最近更新 更多