gpt4 book ai didi

reactjs - React useState Hook 错误 : Argument of type 'xxx' is not assignable to parameter of type 'SetStateAction'

转载 作者:行者123 更新时间:2023-12-03 17:27:56 26 4
gpt4 key购买 nike

我使用 react Hook 进行更新,但在 setState 时会注意到错误。

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



这是我的代码。
import React, { useState, useEffect } from 'react';
import { FieldArray } from 'redux-form';
import { CoordinateSelect } from '~/fields';
import lodash from 'lodash';
import { connect } from 'react-redux';
import { filterDispatchers } from '~/actions';
import t from '~/locale';

interface Props {
getAlertRules(o: object): Promise<any>;
}
type Alert = {
...
}

const connector = connect(
null,
filterDispatchers('getAlertRules'),
);

const AlertRuleForm = (props: Props) => {
const [alertRules, setAlertRules] = useState<Alert[]>([]);
useEffect(() => {
fetchData();
}, []);

const fetchData = async () => {
const actionResult = await props.getAlertRules({ limit: -1 });
const alertRules = lodash.get(actionResult, 'response.alertRules', []);
setAlertRules({ alertRules }); //Error form here
};

const groupedRules = lodash.groupBy(alertRules, 'resourceType');
const levelTypes = lodash.uniq(alertRules.map((alert: Alert) => alert.level));
return (
<FieldArray
name="alertRules"
component={CoordinateSelect}
label={t('告警规则')}
firstOptions={lodash.keys(groupedRules)}
secondOptions={groupedRules}
thirdOptions={levelTypes}
required
/>
);
};
export default connector(AlertRuleForm);


错误是在设置状态时

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

最佳答案

简短回答 :- 从 setAlertRules 语句中删除花括号,因为它会导致 type 之间的不一致的 setAlertRules在定义及其用法。

这是 ES6 的特性,称为 对象文字速记 .

在定义 alertRules 时,setAlertRules 的类型是 SetStateAction 。你试图给它类型 {alertRules: any} 的值,这会导致错误。

传递给 alertRules 的值是一个带有键 alertRules 的对象其值为 Alert 类型的数组.

所以,删除花括号,因为它被转换成这样的东西

 setAlertRules({ alertRules: alertRules  }); 
// now {alertRules: any} this thing will make sense

试试这个代码来更新 alertRules 。
// see no curly braces .
setAlertRules( alertRules );

关于reactjs - React useState Hook 错误 : Argument of type 'xxx' is not assignable to parameter of type 'SetStateAction<xx>' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58709934/

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