简体   繁体   English

如何在 reactjs 中进行 function 异步,它从 redux 操作中调用另外两个函数

[英]How can I make a function Async in reactjs which calls another two functions from redux actions

I am using react, with redux for state management.我正在使用反应,redux 用于 state 管理。 In my UI I have a button which when clicked it calls a function and that function internally calls 2 redux actions that perform the specific task.在我的用户界面中,我有一个按钮,单击该按钮时会调用 function 内部调用 2 个 redux 操作来执行特定任务。 The problem is my function when I make a call after a click of the button it immediately calls both the functions.问题是我的 function 在单击按钮后拨打电话时,它会立即调用这两个功能。

This is my on button click function这是我的按钮点击 function

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 
        }
    });
};

I want to call this function first我想先调用这个 function

props.minusQuantity(productId, props.guestIdData); 

and thnen later the following code然后是以下代码

props.quantityData.forEach((item) => {
        if (item.productQuantity < 1) {  // value of state. Which is instantly changed
            props.removeWholeItem(productId); // Another API call to redux action 
        }
    });

Use redux-thunk and bind your button onClick function as async.使用 redux-thunk 并将您的按钮 onClick function 绑定为异步。

handleClick = async () => {
  await props.actions.someReduxThunkFn();
  await props.actions.otherReduxThunkFn();
}

You can use.then and.catch and makes function calls one after another.您可以使用.then 和.catch 使 function 一个接一个地调用。

props.minusQuantity(productId, props.guestIdData).then(response=>{ props.removeWholeItem(productId) })

Assuming that minusQuantity is a thunk action that returns a promise you can await it:假设 minusQuantity 是一个返回promise 的 thunk 操作,您可以等待它:

const minusQuantity = (productId, guestIdData) => (
  dispatch,
  getState
) => {
  return Promise.resolve('async value');
};

Now both of the other answers would work:现在其他两个答案都可以工作:

const handleDecrement = async (productId) => {
  await props.minusQuantity(productId, props.guestIdData); 

or或者

const handleDecrement = (productId) => {
  props.minusQuantity(productId, props.guestIdData).then(
    ()=>{
      //do other stuff here
    }
  )

Working example:工作示例:

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从ReactJS + Redux应用程序正确地进行REST调用? - How to properly make REST calls from ReactJS + Redux application? 在可以通过redux-observable完成一些异步操作之后,如何对redux操作进行排序? - How can I sequence redux actions after some async action completed in redux-observable? 如何结合这两个异步功能? - How can I combine these two async functions? Vue:如何在 function 数组中相应地使用异步等待,该数组可以为 Promise.all 提供两个功能? - Vue : How to use async await accordingly in a function array of which can have two functions for Promise.all? 如何在 reactjs 中依次调用两个函数 onClick。 两个函数都是异步的 - How call two functions one after another onClick in reactjs. Both functions are async 如何使动作可重用? ReactJS 与 Redux - How can I make an action be reusable? ReactJS with Redux 如何在 Javascript 中使两个函数成为单个函数? - How can I make two functions a single function in Javascript? 如何从另一个动作(redux)导入异步功能? - How to import an async function from another action (redux)? redux thunk 如何调用柯里化的异步 thunk 函数? - How redux thunk calls curried async thunk functions? 如何为两个 redux 操作创建异步/等待结构? - How to create async/await structure for two redux actions?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM