gpt4 book ai didi

reactjs - react typescript 。用对象填充数组状态时出现问题

转载 作者:行者123 更新时间:2023-12-02 02:33:24 25 4
gpt4 key购买 nike

我有以下对象。

const data = [
{
key: '1',
name: 'John Brown',
date: 'Mon Oct 31 2013 00:00:00 GMT-0700 (PDT)',
address: 'New York No. 1 Lake Park',
},
{
key: '2',
name: 'Joe Black',
date: 'Mon Oct 31 2014 00:00:00 GMT-0700 (PDT)',
address: 'London No. 1 Lake Park',
},
{
key: '3',
name: 'Jim Green',
date: 'Mon Oct 31 2011 00:00:00 GMT-0700 (PDT)',
address: 'Sidney No. 1 Lake Park',
},
{
key: '4',
name: 'Jim Red',
date: 'Mon Oct 31 2010 00:00:00 GMT-0700 (PDT)',
address: 'London No. 2 Lake Park',
},
];

还有这个状态

const [usersData, setUsersData] = React.useState([]);

我正在尝试在组件安装时使用 useEffect 设置其数据。

React.useEffect(() => {

setUsersData(result => [...result, data[0]])
props.setLoading(false);
}, []);

But im having an issue with the setUsersData

Argument of type '(result: never[]) => { key: string; name: string;date: string; address: string; }[]' is not assignable to parameter oftype 'SetStateAction<never[]>'. Type '(result: never[]) => { key:string; name: string; date: string; address: string; }[]' is notassignable to type '(prevState: never[]) => never[]'.Type '{ key: string; name: string; date: string; address: string; }[]' is not assignable to type 'never[]'.Type '{ key: string; name: string; date: string; address: string; }' is not assignable to type 'never'.ts

更新:

这就是我目前拥有的。

const data = .... 还是一样

我将 useState 更改为

const [usersData, setUsersData] = React.useState<any[]>([]);

我现在就这样做

React.useEffect(() => {
setUsersData(result => [...result, data[0]])
props.setLoading(false);
}, []);

但是这样它只会将 elemtn 0 添加到我的数组中,而我尝试添加 data 中包含的所有元素

最佳答案

const [usersData, setUsersData] = React.useState([]);

这里的问题是 typescript 将 [] 的类型推断为 never[] ,这意味着空数组。因此,要解决问题,您必须指定为 useState 提供通用参数的类型:

type Item = {
key: string,
name: string,
date: string,
address: string,
}

// It will work even without specifying type here
const data: Item[] = {
//
}

const [usersData, setUsersData] = React.useState<Item[]>([]);

useState 提供类型,表示如果该 Item 事件数组目前为空,则将其写入 typescript 。

关于reactjs - react typescript 。用对象填充数组状态时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64715420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com