【问题标题】:UseState multiple initial statesUseState 多个初始状态
【发布时间】:2021-09-11 18:37:43
【问题描述】:

我正在尝试初始化一个常量变量,该变量可以用作字符串或字符串数​​组,具体取决于我的组件接收的道具。

我正在尝试将其初始化为

const [selectedOptions, setSelectedOptions] = useState<string[] | string>([]);

我意识到这是错误的方式,因为它将状态标识为string[] | string 而不是string[]string。我应该如何去初始化它?

【问题讨论】:

  • 您可以制作一个单独的类型并在这里使用它。但是 bw string[] | stringstring[]string 有什么区别?
  • 你试过双管吗? ||
  • @TusharShahi 单词'string[] | string' 被视为一种类型
  • @Camilo 是的,我收到 Unexpected token 错误。
  • 使用 selectedOptions 值时可以使用类型保护

标签: javascript reactjs typescript frontend


【解决方案1】:

我认为它完全符合您的要求。请参见以下示例:

const [selectedOptions, setSelectedOptions] = useState<string[] | string>([]);

const arrayState: string[] = selectedOptions;

不出所料,Typescript 抛出以下错误:

Type 'string | string[]' is not assignable to type 'string[]'.
  Type 'string' is not assignable to type 'string[]'.(2322)

字符串变量也是如此(反之亦然):

const stringState: string = selectedOptions;

如果您有不同的子组件,以及需要不同类型的道具,那么以下片段应该会有所帮助。

import React, {useState} from 'react';

const SelectionSet = () => {
    const [selectedOptions, setSelectedOptions] = useState<string[] | string>([]);


    if(Array.isArray(selectedOptions)) {
        const arrayState: string[] = selectedOptions;
        return <ComponentA arrayProp={arrayState} />
    } 
    
    
    const stringState: string = selectedOptions;
    
    return <ComponentB stringProp={stringState} />        
}

变量只是出于解释性原因。您还可以使用selectedOptions 状态直接设置道具。

另一方面,如果您想始终在同一个子组件上使用selectedOptions-state,则类似以下几行的解决方案可能是一种解决方案:

const SelectionSet = () => {
    const [selectedOptions, setSelectedOptions] = useState<string[] | string>([]);

    // note the negation 
    if(!Array.isArray(selectedOptions)) {
        return <ComponentC stringProp={selectedOptions} />        
    } 
    
    
    return selectedOptions.map((option, key) => {
        return <ComponentC stringProp={option} key={key} />        
    });    
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 2020-05-19
    • 2022-01-19
    • 2019-08-24
    相关资源
    最近更新 更多