我正在使用react和redux进行状态管理。在我的UI中,我有一个按钮,单击该按钮会调用一个函数,并且该函数会在内部调用2个执行特定任务的redux动作。问题是我的函数,当我单击按钮后打电话时,它立即调用了两个函数。
这是我的按钮点击功能
const handleDecrement = (productId) => {
props.minusQuantity(productId, props.guestIdData); // call make to redux action to perform API action
props.quantityData.forEach((item) => {
if (item.productQuantity < 1) { // value of state. Which is instantly changed
props.removeWholeItem(productId); // Another API call to redux action
}
});
};
我想先调用这个函数
props.minusQuantity(productId, props.guestIdData);
然后在下面的代码
props.quantityData.forEach((item) => {
if (item.productQuantity < 1) { // value of state. Which is instantly changed
props.removeWholeItem(productId); // Another API call to redux action
}
});
假设minusQuantity是一个重击操作,它返回一个可以等待的诺言:
const minusQuantity = (productId, guestIdData) => (
dispatch,
getState
) => {
return Promise.resolve('async value');
};
现在,其他两个答案都可以使用:
const handleDecrement = async (productId) => {
await props.minusQuantity(productId, props.guestIdData);
要么
const handleDecrement = (productId) => {
props.minusQuantity(productId, props.guestIdData).then(
()=>{
//do other stuff here
}
)
工作示例:
const { Provider, connect } = ReactRedux;
const { createStore, applyMiddleware, compose } = Redux;
const initialState = {};
//action types
const BEFORE_ASYNC = 'BEFORE_ASYNC';
const AFTER_ASYNC = 'AFTER_ASYNC';
//action creators
const minusQuantity = () => (dispatch) => {
dispatch({ type: BEFORE_ASYNC });
//note it is returning a promise
return new Promise((resolve) =>
setTimeout(
() => resolve(dispatch({ type: AFTER_ASYNC })),
2000
)
);
};
const reducer = (state, { type }) => {
console.log('reducer called with action:', type);
return state;
};
//creating store with redux dev tools
const composeEnhancers =
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
reducer,
initialState,
composeEnhancers(
applyMiddleware((store) => (next) => (action) =>
typeof action === 'function' //DIY thunk middleware
? action(store.dispatch)
: next(action)
)
)
);
const App = (props) => {
const handleDecrement = (productId) => {
console.log('in handeDecrement starting async action');
props
.minusQuantity(productId)
.then(() =>
console.log('in handleDecrement after async action')
);
};
return (
<button onClick={handleDecrement}>
start async action
</button>
);
};
const AppContainer = connect(undefined, {
minusQuantity,
})(App);
ReactDOM.render(
<Provider store={store}>
<AppContainer />
</Provider>,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/7.2.0/react-redux.min.js"></script>
<div id="root"></div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句