Chr*_*ill 5 reactjs redux redux-thunk
我有一个React/Redux应用程序,负责实时销售(拍卖)的交互式项目列表.我<div id='app'></div>只负责清单.
问题是什么时候和项目被出售,我需要将它添加到另一个列表,这不在React应用程序内.由于列表是在服务器上呈现的,因此它所需的唯一交互是添加这些已售出的项目.
现在我正在做这样的事情
// redux thunk action
export const sellItem = (item) => (dispatch) => {
dispatch(requestSellItem(item)); // set loading state
return fetch('api/sell_item/' + item.id)
.then(response => response.json())
.then(json => {
// remove the item from the React list
dispatch(sellItemSuccess(item.id));
// append the item to the sold items list
// this is the function that puts the sold item in the
// list outside of the React app
appendSoldItem(item);
})
.catch(err => {
// do fallback here
dispatch(sellItemError(err));
});
};
Run Code Online (Sandbox Code Playgroud)
我想知道这是否适合这样做,还是应该把它放在其他地方?
如果您没有想到可以在不“将商品添加到另一个列表”的情况下出售商品的情况,那么这是完全可以接受的。如果不是,您可能希望将销售商品的行为与通知外部服务分离。
无论如何,由于我们正在处理外部服务,我认为这是中间件层的完美示例。这是一个例子:
import { ITEM_SOLD_SUCCESS } from ... // Import same action created by sellItemSuccess()
let itemSoldNotifier = store => next => action => {
if (action.type === ITEM_SOLD_SUCCESS) {
// Notify the external service that the item was sold
appendSoldItem(action.item); // Assuming that the action contains the item sold itself
}
return next(action);
}
Run Code Online (Sandbox Code Playgroud)
以下是在商店中应用该图层的方法:
let store = createStore(
combineReducers(reducers),
applyMiddleware(
itemSoldNotifier
)
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
415 次 |
| 最近记录: |