0

我的经验主要是 React Hooks & Context,其中定义了 Actions & Reducers。然后将 Actions 导入 React 组件并通过 Dispatch 函数调用。

在一个新项目中,我必须使用 React Hooks 和 Redux。这里我使用的是 Action Creators & Reducers。这是我创建的 Action Creator 的示例:

export const fetchCompanies: ActionCreatorThunk = () => {
  return function (dispatch, getState) {
    dispatch({ type: FETCH_COMPANIES_REQUEST });

    requests
      .get(
        `${requests.API_ROOT()}companies`,
        null,
        true
      )
      .then((response) => {
        dispatch({ type: FETCH_COMPANIES_SUCCESS, payload: response.data.companies });
      })
      .catch((error) => {
        console.error(error);
        dispatch({ type: FETCH_COMPANIES_FAILURE, payload: error.response });
      });
  };
};

这很好用。

这是我的情况:我需要有一个动作来创建一个“空”的公司,所以没有必要创建一个动作创建者。因此我创建了一个这样的动作:

export const INIT_EMPTY_COMPANY: ActionType = 'INIT_EMPTY_COMPANY';
export type InitEmptyCompanyAction = { type: typeof INIT_EMPTY_COMPANY };

使用 Action Creator,我从内部调用它,useEffect如下所示:

dispatchRedux(fetchCompanies());

使用 Action,我想我可以以与我一直使用 Context 调用动作的方式类似的方式调用它,如下所示:

dispatchRedux({ type: InitEmptyServiceFormAction });

不幸的是,我收到了这个流错误:“无法 InitEmptyCompanyAction从值位置引用类型 [1]。”

我做错了什么以及如何解决这个问题?

4

1 回答 1

1

我想通了,但我觉得我以前没见过它很愚蠢。我不知何故在我的脑海里想到了那INIT_EMPTY_COMPANY是一种类型。它确实有一个类型,即ActionType但它本身不是一个类型。我的失败是试图将它作为一种类型导入。

需要更多的睡眠,我猜!

于 2020-11-23T03:21:50.080 回答