【问题标题】:redux thunk calling two different api requestsredux thunk 调用两个不同的 api 请求
【发布时间】:2016-12-15 06:17:22
【问题描述】:

试图在一个动作中调用两个 api。当一个完成时调用另一个然后在最后一个将其传递给减速器。 看起来我的 getAttending 在发布的同时被调用,而不是在发布完成后被调用。我是 redux-thunk 的新手,并认为我可以将它们一个接一个地称为已完成。

   export function postDeclined(id){
        let post = axios.post(blaBla.com);
        let getAttending = axios.get(attending.com);
        return (dispatch) => {
            post.then(()=>{
                getAttending.then(({data})=>{
                    dispatch({
                        type: type.NOT_GOING,
                        payload: data.data
                    });
                });
            });
        }
    }

【问题讨论】:

    标签: reactjs redux react-redux redux-thunk


    【解决方案1】:

    尝试像这样进行 api 调用:

     export function postDeclined(id){
            return (dispatch) => {
                 axios.post(blaBla.com).then(()=>{
                     axios.get(attending.com).then(({data})=>{
                        dispatch({
                            type: type.NOT_GOING,
                            payload: data.data
                        });
                    });
                });
            }
        }
    

    当您“声明”调用时,您实际上是在调用 API……所以它正在执行异步操作……

    【讨论】:

      【解决方案2】:

      我会将 async/await 添加到您的 babel 配置中。使阅读/调试这些东西变得更加容易。

      export const postDeclined => (id) => async (dispatch) => {
        const post await axios.post(blaBla.com);
        const getAttending = await axios.get(attending.com);
        return dispatch({
          type: type.NOT_GOING,
          payload: getAttending.data
        });
      };
      

      【讨论】:

      • postDeclined => (id) => async (dispatch) => 什么是来自 await 的异步方法?或者只是包装链方法的名称。
      • async 关键字创建了一个返回承诺的函数。 await 关键字使该行成为同步调用,并且在 promise 被解决之前不会继续。 github.com/tc39/ecmascript-asyncawait
      【解决方案3】:

      代码示例存在一个非常常见的问题。该函数同时做两件事:调用 apis 和调度一个动作。另外,请注意,您可以链接 Promises,不需要中间回调:

       export const postDeclined = id =>
         axios.post(blaBla.com).then(axios.get(attending.com));
      
       export const notifyNotGoing = dispatch => promisedResult =>
         promisedResult.then(({data}) =>
           dispatch({
             type: type.NOT_GOING,
             payload: data.data
           })
         );
      

      然后你可以这样调用你的函数:

      notifyNotGoing(dispatch)(postDeclined(2))
      

      或者使用组合和柯里化(我个人更喜欢Ramda

      const prog = compose(notifyNotGoing(dispatch), postDeclined)
      prog(2)
      

      【讨论】:

        猜你喜欢
        • 2023-03-13
        • 2019-08-05
        • 2020-07-21
        • 2019-01-24
        • 2018-12-02
        • 2018-06-06
        • 2017-02-04
        • 2018-11-10
        • 2017-08-28
        相关资源
        最近更新 更多