【问题标题】:How to useDispatch async multiple times?如何多次使用Dispatch async?
【发布时间】:2021-05-27 14:37:04
【问题描述】:

我使用 useDispatch 两次来更改我的待办事项,然后更改我的登录状态。两者都是分开工作的,但是当它们放在一起时,第二次调度会将我的待办事项列表覆盖到一个空对象 []。 我将如何进行这项工作?

Axios 发布

axios
      .post("http://localhost:3333/user/login", newUser)
      .then((response) => {
        //do stuff
        dispatch(changeTodos(stuff));
        dispatch(login());
      });

操作

export const login = (data) => {
  return {
    type: "LOGIN",
    data: data,
  };
};

export const changeTodos = (data) => {
  return {
    type: "CHANGETODOS",
    data: data,
  };
};

减速器

const loggedReducer = (state = false, action) => {
  switch (action.type) {
    case "LOGIN":
      return true;

    case "LOGOUT":
      return false;

    default:
      return false;
  }
};

export default loggedReducer;

const todosReducer = (state = [], action) => {
  switch (action.type) {
    case "CHANGETODOS":
      return action.data;

    default:
      return [];
  }
};

export default todosReducer;

【问题讨论】:

    标签: reactjs asynchronous redux axios redux-thunk


    【解决方案1】:

    对于您的默认值,您需要返回状态,否则当它与操作类型不匹配时,它将达到默认值。例如,LOGIN 将使您的 TodosReducer 返回[],这就是它被清除的原因。

        default:
          return state;
    

    【讨论】:

      猜你喜欢
      • 2018-09-18
      • 1970-01-01
      • 1970-01-01
      • 2020-04-28
      • 2012-06-16
      • 2020-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多