我使用 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
允许您的 Action 创建者(如 postOrder
)返回一个函数,然后将相应的 Action (具有 type
和 payload/data
属性的对象)分派(dispatch)到商店。您可以发送任意数量的操作。POST
只是一个 HTTP
我用来发布订单的动词,你可以在这里看到。首先,POST_ORDERS_REQUEST
是您的请求的开始,您可以在其中显示正在加载... 状态或应用程序中的微调器。所以,这个 Action 触发了,orderReducer
检查什么 type
of action 已经到达,然后相应地执行并将数据存储在 redux-store 中。我相信你知道基本的 redux,所以理解这一切对你来说可能不是问题。其他两个 Action 的工作方式相同。
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/
关于api - Redux 中间件,POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60937405/