【问题标题】:React Hooks - JSDoc with destructured array variablesReact Hooks - 具有解构数组变量的 JSDoc
【发布时间】:2020-01-18 10:22:26
【问题描述】:

我正在尝试 JSDoc 一个带有钩子的简单 React Typescript 组件。不幸的是,我似乎找不到使 JSDoc 与声明的解构数组一起工作的方法。有 some answers 与解构对象参数相关,但这些不适用于数组。

/**
 * @property {boolean} 0 - documentation for isLoading
 * @property {func} 1 - documentation for setIsLoading
 */
 const [isLoading, setIsLoading] = React.useState<boolean>(false);

更新 1:仍然无法找到记录这种解构的方法。有一个极端情况,如果我自定义类型一个对象,它可以工作:

export type AuthFormInput = {
  /** Value of the Email input field */
  email: string;
  /** Value of the Password input field */
  password: string;
};

const [form, setForm] = React.useState<AuthFormInput>({
  email: '',
  password: ''
});

...

// JSDoc will work here
const email = form.email;

【问题讨论】:

  • 您是否发布了所有相关代码?我没有看到对 JSDoc 或解构数组的任何引用。
  • @RutherfordWonkington JSDoc 确实是单行代码上方的注释块。解构后的数组在const [isLoading, setIsLoading]
  • 所以你想要 JSDoc 局部变量,对吗?如果有,需要什么?
  • @skyboyer 主要用于记录组件状态,以便以后使用时可以提出对它的引用。

标签: reactjs typescript jsdoc3


【解决方案1】:

这会有所帮助:

    /**
     * @typedef {Boolean} LoadingState — documentation for isLoading
     * @description Additional doc
     */
    /**
     * @typedef {Function} LoadingStateSetter — documentation for setIsLoading
     */
    /**
     * @type {[LoadingState, LoadingStateSetter]} Loading
     */
    const [isLoading, setIsLoading] = React.useState();

在此示例中,我们声明了两个附加类型:LoadingStateLoadingStateSetter。然后我们为它们添加一些描述,最后,我们为React.useState()的结果声明Loading类型

你也可以用更简单的方式声明它:

    /**
      * @type {[Boolean, Function]} Loading
      */
    const [isLoading, setIsLoading] = React.useState();

但在这种情况下,我没有找到添加描述的方法。

我已经在 VSCode 中检查了这种文档方式的描述

【讨论】:

    【解决方案2】:

    你可以试试这个:

    /** @type {boolean} */
    const initialState = false
    const [isLoading, setIsLoading] = React.useState(initialState)
    

    【讨论】:

    • 这样更好,因为 typescript 会自行推断 isLoading 和 setIsLoading 的类型 +1。 setIsLoading 比Function 复杂,就是React.Dispatch&lt;React.SetStateAction&lt;boolean&gt;&gt;
    • 请注意,这仅在变量可以保存一种类型时才有效 - 这意味着如果您想要一个可为空的值,例如,它只会推断出部分类型(即使您指定了类型变量)。老实说有点烦人......
    【解决方案3】:

    在此处找到的实际最佳解决方案是使用括号。否则 jsdoc 似乎没有抓住它:

    const [authFormInput, setAuthFormInput] = useState(/** @type {AuthFormInput} */({..}));
    

    【讨论】:

      【解决方案4】:

      我发现最简洁的方法是使用types.d.ts,因为我们可能需要输入的不仅仅是useState,而且我们可以保留大量代码以保持简洁:

      // types.d.ts:
      declare type State = string;
      declare type SetState = (stateParam: State) => void;
      declare type UseState = [State, SetState];
      
      // component.jsx:
        /**
         * @type {UseState}
        */
        const [state, setstate] = useState("");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-07
        • 1970-01-01
        • 1970-01-01
        • 2018-08-02
        • 2020-09-18
        • 2019-10-03
        • 1970-01-01
        • 2020-03-21
        相关资源
        最近更新 更多