【问题标题】:Redux dispatch action not firingRedux 调度操作未触发
【发布时间】:2021-03-15 10:28:44
【问题描述】:

我正在尝试触发这个 redux 操作,但每当我检查减速器有效负载的值时,由于某种原因它总是“未定义”。这只会让我认为动作没有触发,我不明白为什么。这是我的行动:

export const getAllSubmittedRequests = (people: PersonalData[]) => (dispatch: any) => {
  let count = 0;
  people?.forEach((person) => {
    if (person.isEntered === true) {
      count++;
    }
  });

  dispatch(getAllSubmittedRequestsSuccess(count === people?.length ? true : false));
};

getAllSubmittedRequestsSuccess:

export const getAllSubmittedRequestsSuccess = (enteredRequests: boolean) => ({ type: GET_ENTERED_REQUESTS, enteredRequests});

这是减速器的部分,非常简单:

case GET_ENTERED_REQUESTS:
  return { ...state, enteredRequests: action.enteredRequests};

我在组件中的 useEffect 挂钩中调用我的操作,如下所示:

  useEffect(() => {
    getAllSubmittedRequests(props.data.people);
  }, [props.data.people]);

谁能告诉我我在使用 getAllSubmittedRequests 时做错了什么以及为什么 dispatch 部分没有在操作函数内触发?

【问题讨论】:

    标签: reactjs typescript redux


    【解决方案1】:

    是的,您正在创建一个函数并将其丢弃。 getAllSubmittedRequests(...) 返回一个以 dispatch 函数作为参数的函数。你忘了叫它:

    const dispatch = useDispatch();
    useEffect(() => {
        getAllSubmittedRequests(props.data.people)(dispatch);
    }, [props.data.people]);
    

    【讨论】:

    • 不,这是一个 thunk,redux-thunk 中间件会处理这个问题。真的应该叫dispatch(getAllSubmittedRequests(props.data.people))
    • @phry 我从未使用过 thunk 中间件,但我认为它会钩住寻找函数的动作管道。说得通。鉴于问题中没有此信息,我很高兴保持原样并在 cmets 中保留 thunk 中间件的相关性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-06
    • 2023-03-03
    • 2017-10-18
    相关资源
    最近更新 更多