为钩子设置React / Redux打字稿

凯文

我一直在网上寻找不同的资源,试图找到适合我所拥有的解决方案,到目前为止,我认为我有点在破坏我的打字稿集成。我希望在正确设置钩子类型方面有所帮助。

我有一个useUser()钩子,可将动作分派给我的减速器,也可将选择器从我的商店退回。我已经取得了一些进步,但是我开始有点头疼了。

挂钩: useUser.ts

  • 我不确定该放置什么作为钩子的回报。我试图把useUserActionTypes,但我不认为这有什么差别,特别是因为我不返回任何东西确实出乎要么得到一个对象(userData),或一个数字(totalPointstotalWords从商店)。
  • 我不认为我应该“退回”我的派遣单,但是这使打字稿的烦恼减轻了
  • 我也可以只输入“ Dog”FETCH_USER之类的内容,而不是例如输入我的调度员的类型。可能无关紧要,但是我认为其中应该有保护措施,对吗?
  • 如何在非结构化回报中实际修复该错误非常困扰。我有一个名为的类型User,表示我的商店将为用户提供的对象,但是...没什么区别。
import { useSelector, useDispatch } from 'react-redux';
import axios from 'axios';
import { User } from '../reducers/user';

export const FETCH_USER = 'FETCH_USER';
export const UPDATE_ERRORS = 'UPDATE_ERRORS';
export const INCREMENT_POINTS = 'INCREMENT_POINTS';
export const INCREMENT_WORDS = 'INCREMENT_WORDS';

type Error = {
  code: number;
  message: string;
};

type FetchUserAction = {
  type: typeof FETCH_USER;
  payload: User;
};

type UpdateErrorsAction = {
  type: typeof UPDATE_ERRORS;
  payload: Error[];
};

type IncrementPointsAction = {
  type: typeof INCREMENT_POINTS;
  payload: number;
};

type IncrementWordsActions = {
  type: typeof INCREMENT_WORDS;
};

// ? Typescript is able to infer the correct type in the Union Type below
export type useUserActionTypes =
  | FetchUserAction
  | UpdateErrorsAction
  | IncrementPointsAction
  | IncrementWordsActions;

export type ReduxStore = {
  alert: any;
  user: User;
};

const useUser = (): useUserActionTypes => {
  const userData: User = useSelector((state: ReduxStore) => state.user);
  const totalPoints: number = useSelector(
    (state: ReduxStore) => state.user.points
  );
  const totalWords: number = useSelector(
    (state: ReduxStore) => state.user.words
  );
  const dispatch = useDispatch();
  const fetchUser = async (): Promise<FetchUserAction | UpdateErrorsAction> => {
    try {
      const response = await axios.get(
        'http://localhost:5000/api/v1/users/WhpHq4qWFdzlhlx2ztqD'
      );
      const user = response.data;
      return dispatch({
        type: FETCH_USER,
        payload: user,
      });
    } catch (error) {
      return dispatch({
        type: UPDATE_ERRORS,
        payload: [
          {
            code: 500,
            message: error.message,
          },
        ],
      });
    }
  };
  const incrementPoints = (amount: number): useUserActionTypes => {
    return dispatch({
      type: INCREMENT_POINTS,
      payload: amount,
    });
  };
  const incrementWords = (): useUserActionTypes => {
    return dispatch({
      type: INCREMENT_WORDS,
    });
  };
  return {
    userData,
    totalPoints,
    totalWords,
    fetchUser,
    incrementPoints,
    incrementWords,
  };
};

export default useUser;

在此处输入图片说明


在我尝试使用选择器的页面上:

  • 我以为这些都在我的钩子中涵盖了,我为这些常量分配了类型。
  • fetchUser() 返回“ any”类型...可能与上述相同?

在此处输入图片说明

在此处输入图片说明

谢谢您的帮助,尝试将所有内容与打字稿正确地连接起来绝对很有趣,但是我现在有点迷茫。

埃里亚斯·舍布洛夫斯基(Elias Schablowski)

问题是您键入useUser错误,根据您的代码正确的返回类型将是:

{
    userData: User;
    totalPoints: number;
    totalWords: number;
    fetchUser(): Promise<FetchUserAction | UpdateErrorsAction>;
    incrementPoints(amount: number): useUserActionTypes;
    incrementWords(): useUserActionTypes;
}

操场

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章