Redux 中间件,POST 请求

Redux Middleware, POST Request

我使用 redux api middleware 编写了用于发送请求的函数。 POST 函数代替 GET 是什么样的?

RSAA getOrdersRequest(){
  return RSAA(
    method: 'GET',
    endpoint: 'http://10.0.2.2:80/order',
    types: [
      LIST_ORDERS_REQUEST,
      LIST_ORDERS_SUCCESS,
      LIST_ORDERS_FAILURE,
    ],
    headers: {
      'Content-Type':'application/json',
    },
  );
}

ThunkAction<AppState> getOrders() => (Store<AppState> store) => store.dispatch(getOrdersRequest());

我的函数是用dart写的,但是例子的语言并不重要,

感谢您的帮助

要进行异步调用,您应该使用像 redux-thunk 这样的中间件。我将在这里使用 JavaScript。

关于 thunk,你只需要知道 redux-thunk 允许你的动作创建者(如 postOrder)return 一个函数,然后分派相应的动作(带有 [= 的对象) 15=] 和 payload/data 属性) 到商店。您可以根据需要分派任意数量的操作。

POST 只是一个 HTTP 动词,我用它来 post 一个命令,正如你在下面看到的那样。首先,POST_ORDERS_REQUEST 是您请求的开头,您可以在其中显示加载...状态或应用程序中的微调器。所以,这个动作触发,orderReducer 检查什么 type 动作已经到达,然后相应地动作并将数据存储在 redux-store 中。我确定您了解基本的 redux,因此理解所有这些对您来说可能不是问题。其他两个动作同理。

export const postOrder = () => {
  return async (dispatch) => {
    dispatch({
      type: POST_ORDER_REQUEST
    })
    try {
      const res = await axios.post("http://10.0.2.2:80/order",
        {
          headers: {
            "Content-Type": "application/json",
          }
        })
      dispatch({
        type: POST_ORDER_SUCCESS,
        data: { order: res.data.order }
      })
    } catch (err) {
      dispatch({
        type: POST_ORDER_FAILURE,
        data: { error: `Order failed with an ${err}` }
      })
    }
  }
}

您可以相应地创建您的 orderReducer,例如:

const initialState = {
  isLoading: false,
  myOrder: null,
  error: null
}

export const orderReducer = (state = initialState, action) => {
  switch (action.type) {
    case POST_ORDER_REQUEST:
      return {
        ...state,
        isLoading: true,
        error: null
      }
    case POST_ORDER_SUCCESS:
      return {
        ...state,
        isLoading: false,
        myOrder: action.data.order,
        error: null
      }
    case POST_ORDER_FAILURE:
      return {
        ...state,
        isLoading: false,
        error: action.error
      }
    default:
      return state
  }
}

您可以阅读这些关于 Redux 的好文章,您可能会喜欢:

https://daveceddia.com/what-is-a-thunk/

https://daveceddia.com/where-fetch-data-redux/

由于接受的响应与 redux api middleware 无关,redux api middleware 是为了减少“boilerplatish”和重复的 thunk 代码,您可以使用 redux-api-middleware 中的 createAction,例如:

import { createAction } from "redux-api-middleware";

export const getOrders = () =>
  createAction({
    endpoint: 'http://10.0.2.2:80/orders',
    method: "GET",
    types: ['GET_ORDERS_PENDING', 'GET_ORDERS_SUCCESS', 'GET_ORDERS_FALED'],
  });

export const getOrderById = (id) =>
  createAction({
    endpoint: `http://10.0.2.2:80/orders/${id}`,
    method: "GET",
    types: ['GET_ORDER_BY_ID_PENDING', 'GET_ORDER_BY_ID_SUCCESS', 'GET_ORDER_BY_ID_FALED'],
  });

export const submitOrder = (name, price) =>
  createAction({
    endpoint: 'http://10.0.2.2:80/orders',
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      name: name,
      price: price,
    }),
    types: ['SUBMIT_ORDER_PENDING', 'SUBMIT_ORDER_SUCCSESS', 'SUBMIT_ORDER_FAILED'],
  });

如果你可以使用比简单的 api 服务调用更多的处理,你总是可以将它与 thunk 结合起来,比如 this