我开始在 reactjs 中学习 redux。我正在尝试为 redux 实现一个异步结构,但我真的很困惑......
要实现异步函数并使用 promise,您应该在函数之前键入 async 并在使用 promise 之前使用 await。
但在许多示例中,我从未见过他们在函数之前使用异步并在 promise 变量之前使用等待。
例如看这两个链接:
https://redux.js.org/advanced/async-actions
https://github.com/reduxjs/redux/tree/master/examples/async
那么如何在 reducer 中调用异步函数并返回异步结果呢?
例如,我想用异步函数准备这个列表,然后用 axios 或 fetch API 获取列表:
const list = [
{id: 1, title: 'One'},
{id: 2, title: 'Two'},
{id: 3, title: 'Three'}
]
export function newsReducer(state = [], action) {
switch (action.type) {
case 'GET_NEWS':
return list
default:
return state
}
}
最佳答案
总而言之,我建议理解 Action 、 reducer 和存储的概念。
- 一个 Action 是一个或多个 reducer 案例的触发器
- 商店已开启,所有数据都包含在内,只有 reducer 可以使用他们从商店"dispatch"获得的方法更改它
- reducer 是一段代码,可在商店中产生不可变的更改。
因此,为了同步更改存储,您必须调用存储方法 dispatch
,以便 reducer 触发并更改您期望的内容。
要执行异步操作,您必须在异步调用完成后调用 reducere。
例子:
// action method called by react component when user submits changes
export function updateProduct(product) {
// returns a function since this method has to be called also with dispatch() in the component
return dispatch => {
// trigger first store change
dispatch({ type: PRODUCT_EDIT.PRODUCT_EDIT_REQUEST });
// trigger secod store change and mark the async call, updateProduct is ASYNC
ProductsService.updateProduct(product)
.then(
res => {
dispatch({ type: PRODUCT_EDIT.PRODUCT_EDIT_SUCCESS, data: res.data });
dispatch(successNotification('Product updated'));
},
error => {
dispatch({ type: PRODUCT_EDIT.PRODUCT_EDIT_FAILURE, data: error.response.data });
dispatch(errorNotification(error.response.data));
}
);
};
}
我认为您应该查看的其他教程: https://medium.com/@rajaraodv/step-by-step-guide-to-building-react-redux-apps-using-mocks-48ca0f47f9a
关于javascript - 异步 redux 函数如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50461682/