redux thunk函数上的调用dispatch如何工作?

问题描述

我下面有一个名为setAlert的高阶函数,可以通过传递dispatch方法作为其参数来重调用它返回的函数。

// Action Creators
import { SET_ALERT,REMOVE_ALERT } from "./types";
import { v4 as uuid } from "uuid";

export const setAlert = (msg,alertType,timeout = 5000) => (dispatch) => {
  const id = uuid();
  dispatch({
    type: SET_ALERT,payload: { id,msg,alertType },});
  setTimeout(() => dispatch({ type: REMOVE_ALERT,payload: id }),timeout);
};

这里有另一个名为register的函数,该函数发出axios发布请求,当请求失败时,调度上面定义的setAlert函数。

import axios from "axios";
import { REGISTER_SUCCESS,REGISTER_FAIL } from "../actions/types";
import { setAlert } from "./alert";

// Register
export const register = ({ name,email,password }) => async (dispatch) => {

  [some code ...]

  try {

    [code handling successful request ...]

  } catch (err) {
    const errors = err.response.data.errors;
    if (errors)
      errors.forEach((error) => dispatch(setAlert(error.msg,"danger")));**

    dispatch({
      type: REGISTER_FAIL,});
  }
};

问题:

  1. 我们为什么不直接打setAlert
  2. dispatch(setAlert(err.msg,'danger'))如何工作?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)