我的经验主要是 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]。”
我做错了什么以及如何解决这个问题?