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

问题描述 投票:0回答:1

我收到此错误

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);
 }, []);
javascript typescript interface
1个回答
0
投票
Argument of type 'MyInterface[]'
                  -----------^^

is not assignable to parameter of type 'SetStateAction<MyInterface | null>.
                                                       -----------

现在看到问题了吗?


您有一个

MyInterface
状态,但您尝试将
MyInterface
数组分配给该状态。

所以您可能想输入您的状态来接受

MyInterface[]

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

看游乐场

© www.soinside.com 2019 - 2024. All rights reserved.