lom*_*ans 11 typescript reactjs tsx react-hooks
我使用 react hooks 来更新,但是在 setState 时会注意到错误。
'{ alertRules: any; 类型的参数 }' 不能分配给'SetStateAction' 类型的参数。对象字面量只能指定已知属性,并且类型“SetStateAction”中不存在“alertRules”.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);
Run Code Online (Sandbox Code Playgroud)
错误是在设置状态时
'{ alertRules: any; 类型的参数 }' 不能分配给'SetStateAction' 类型的参数。对象字面量只能指定已知属性,并且类型“SetStateAction”中不存在“alertRules”.ts(2345)
简短回答:- 从 setAlertRules 语句中删除大括号,因为它会导致type
ofsetAlertRules
的定义与其用法之间不一致。
这是 ES6 的功能,称为“对象文字速记”。
在定义alertRules时,setAlertRules的类型是SetStateAction<Alert[]>。并且您试图为其赋予类型为{alertRules: any}的值,这会导致错误。
传递给的值alertRules
是一个带有键的对象alertRules
,其值是类型为 的数组Alert
。
因此,删除花括号,因为它会转换为这样的内容
setAlertRules({ alertRules: alertRules });
// now {alertRules: any} this thing will make sense
Run Code Online (Sandbox Code Playgroud)
尝试此代码来更新alertRules。
// see no curly braces .
setAlertRules( alertRules );
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12116 次 |
最近记录: |