三行代码  ›  专栏  ›  技术社区  ›  programmerGuy

使用useState时获取不可分配给参数的接口

  •  2
  • programmerGuy  · 技术社区  · 3 月前

    我收到这个错误 Argument of type 'MyInterface[]' is not assignable to parameter of type 'SetStateAction<MyInterface | null>. 我不知道在这里该做什么。我觉得我以前遇到过这种情况,但不确定我做了什么来解决它。以下是我所拥有的:

    interface MyInterface {
      email: string;
      name: string;
    }
    
    const [selection, setSelection] = useState<MyInterface | null>(null);
    
    //defaultValue is being populated from a query pull and it is of type MyInterface[]
    
    useEffect(() => {
       setSelection(defaultValue);
     }, []);
    
    2 回复  |  直到 3 月前
        1
  •  1
  •   AztecCodes    3 月前

    修复React中的“Argument Not Assignable”错误

    您在中遇到了类型不匹配的经典问题 TypeScript 。让我们来分解一下:

    您的状态选择设置为容纳类型为的单个对象 MyInterface null 。但是你试图赋予它的价值, defaultValue ,是 MyInterface 对象。想象一下,这就像试图把一整托盘杯子装进一个杯子支架里。这行不通。

    让我们来解决这个问题:

    1.如果您希望选择只存储一个MyInterface对象:
    从中拾取第一个对象 defaultValue :

    setSelection(defaultValue[0]);
    

    但是,如果有可能 defaultValue 可能是空的,请小心:

    setSelection(defaultValue.length > 0 ? defaultValue[0] : null);
    

    2.如果你愿意 selection 以便能够容纳整个阵列:
    您需要修改设置状态的方式,以便 MyInterface 对象或 无效的 应为:

    const [selection, setSelection] = useState<MyInterface[] | null>(null);
    

    现在有了这些更改 defaultValue 选择 应正确工作:

    setSelection(defaultValue);
    

    您选择的选项取决于您的用例。当然,关键是要确保你所处理的价值观类型之间的适当一致。

        2
  •  0
  •   Alex Wayne    3 月前
    Argument of type 'MyInterface[]'
    //                -----------^^
    
    is not assignable to parameter of type 'SetStateAction<MyInterface | null>.
    //                                                     ---------^^
    

    现在看到问题了吗?


    你的州是 MyInterface ,但您正试图分配一个 MyInterface 到那个状态。

    所以你可能想键入你的州来接受 MyInterface[] 相反

    const [selection, setSelection] = useState<MyInterface[] | null>(null);
    

    See Playground