【问题标题】:How to declare useState() initial value as null and then give it an object value later?如何将 useState() 初始值声明为 null,然后再给它一个对象值?
【发布时间】:2022-07-05 22:36:55
【问题描述】:

如图所示,我想为我的网页警报声明一个反应状态挂钩。起初,我希望没有显示警报。并且每当用户单击某个按钮时,我想显示一个带有消息的成功警报(如果出现问题,则会出现错误警报)。我将调用 showAlert 函数来执行此操作,并将消息和类型作为函数参数。这就是为什么会有不止一种类型的警报。所以,我创建了这个警报对象并附加了初始值为“NULL”的钩子。但是编辑器给了我这个错误。

Argument of type '{ msg: any; type: any; }' is not assignable to parameter of type 'SetStateAction<null>'. Object literal may only specify known properties, and 'msg' does not exist in type '(prevState: null) => null'.ts(2345)

那么,谁能告诉我如何告诉 useState 对象参数,我将在未来分配它。或者我应该尝试以其他方式隐藏网站警报?这是代码..

const [alert, setAlert] = useState(null);

const showAlert = (message, type) => {
    setAlert({
        msg: message,
        type: type,
    });

    setTimeout(() => {
        setAlert(null);
    }, 2000);

【问题讨论】:

  • 请将代码图片替换为基于文本的minimal reproducible example
  • 定义状态类型useState(null as any)
  • useState&lt;{msg: string, type: string}&gt;(null)。如果您在 tsconfig 中有严格的 null 检查,您将无法设置 null。您可以从 tsconfig 中删除它,也可以useState&lt;{msg: string, type: string} | null&gt;(null)
  • @Rashomon 我试过了。我得到这两个错误。 1. 解析错误:Unexpected token, expected "," (10:41)eslint {squigly error on null word} 2. 类型断言表达式只能在TypeScript files.ts(8016) {error line under any word}
  • @Dilshan 我为您的解决方案收到了这些错误。 1. 类型 'number' 必须有一个返回 iterator.ts(2488) 的 '[Symbol.iterator]()' 方法 2. (property) msg​​: any Operator ' (initialState: S | (() => S)): [S, Dispatch>]; (): [S |未定义,调度>]; }' 和 '{ 味精:任何;类型:任何; }'.ts(2365) '|'布尔类型不允许使用运算符。考虑使用“||”相反.ts(2447) 3. 与自身进行比较可能毫无意义。eslintno-self-compare Object 可能为 'null'.ts(2531)

标签: javascript reactjs typescript react-hooks use-state


【解决方案1】:

你需要声明你的 useState 有点不同

const [alert, setAlert] = useState<{ msg: any; type: any } | null>(null);

另一种选择是使用undefined

const [alert, setAlert] = useState<{ msg: any; type: any } | undefined>();

希望对您有所帮助。

【讨论】:

    【解决方案2】:

    对于 useState 类型,您可以按照以下方式进行操作

    type AlertType = {
     msg: string;
     type: string; // you can specify enum also
    }
    
    const [alert, setAlert] = useState<AlertType|null>(null);
    
    const showAlert = (message, type) => {
        setAlert({
            msg: message,
            type: type,
        });
    
        setTimeout(() => {
            setAlert(null);
        }, 2000);
    

    【讨论】:

      【解决方案3】:

      有两种解决方案:

      1: useState(null as any)
      2: useState({ msg: any, type: any })
      

      【讨论】:

        【解决方案4】:

        从您提到的错误的外观来看,您似乎正在使用 TypeScript。

        达到预期结果的一种方法是使用generics

        const [alert, setAlert] = useState<{
          msg: string;
          type: "success" | "error";
        } | null>(null);
        

        此外,您可以添加enum 和类型。

        enum AlertType {
          Success,
          Error,
        }
        
        type Alert = {
          msg: string;
          type: AlertType;
        }
        
        const [alert, setAlert] = useState<Alert | null>(null);
        

        【讨论】:

          猜你喜欢
          • 2011-04-15
          • 1970-01-01
          • 2021-02-08
          • 1970-01-01
          • 1970-01-01
          • 2021-12-22
          • 2012-03-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多