【问题标题】:Promise chain cannot accept my parametersPromise 链不能接受我的参数
【发布时间】:2018-06-07 15:22:38
【问题描述】:

我在链接分配有参数的承诺时遇到问题:

这是我的初始链:

dispatchTermsCondition(history, dispatch)
        .then((history, dispatch)=>
             dispatchSetPrivacy(history, dispatch)
         )
         .then(()=>
                dispatcherUserTermsPrivacy(history,dispatch, getState,response.data.tj_id)
          );

第一个链工作正常,第二个链找不到我发送给它的参数。 这是我的第二个函数(dispatchSetPrivacy):

export function dispatchSetPrivacy(history, dispatch) {
return axios.get("some url")
    .then((response) => {
        dispatch({
            type: SET_PRIVACY,
            payload: {
                privacy: {id: response.data.id, content: response.data.content, version: response.data.version }
            }
        });

    }).catch(function(response){


        console.log(response);
        history.push("/error");
    });
 }

这是我得到的错误:

TypeError: dispatch is not a function 在 bundle.js:76071

它发生在 dispatchSetPrivacy 中。

有什么想法吗?

【问题讨论】:

  • 首先,我想说您在 dispatchSetPrivacy 和 dispatcherUserTermsPrivacy 之前缺少“returns”语句。
  • then 回调只接受一个参数。仅使用history => 而不是(history, dispatch)=> 并从周围环境中获取dispatch
  • @Gnujeremie 不,返回值隐含在没有块体的箭头函数中
  • 可以显示周边代码吗?任何导入、参数声明、初始化等?
  • @DominicTobias 我的错,你是对的,请添加它作为答案,我会接受它

标签: javascript ecmascript-6 promise axios


【解决方案1】:

所以这一行:

.then((history, dispatch) =>
  dispatchSetPrivacy(history, dispatch)
)

将返回dispatchSetPrivacy 的结果,但在.then 中没有返回任何内容,因此不会有任何参数。如果你想传递参数然后在返回中传递一些东西,例如:

export const dispatchSetPrivacy = (history, dispatch) =>
    axios.get("some url")
      .then((response) => {
        dispatch({
          type: SET_PRIVACY,
          payload: {
            privacy: { id: response.data.id, content: response.data.content, version: response.data.version }
          }
        });
        return response;
      })
      ...

没有必要传递调度和历史,因为它们可以从上层范围(redux thunk)获得,你应该可以从那里使用它们:

const yourThunk = (history, otherArg) => (dispatch, getState) => {
  dispatchTermsCondition(history, dispatch)
    .then(() =>
      dispatchSetPrivacy(history, dispatch)
    )
    .then((response) =>
      dispatcherUserTermsPrivacy(history, dispatch, getState, response.data.tj_id)
    );
};

注意不完全确定历史是来自模块还是来自参数,但你明白了!

【讨论】:

    猜你喜欢
    • 2019-11-06
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    • 2016-11-17
    • 1970-01-01
    相关资源
    最近更新 更多