【发布时间】:2020-03-01 17:51:11
【问题描述】:
我使用 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);
错误是在设置状态时
'{ alertRules: any; 类型的参数}' 不可分配给“SetStateAction”类型的参数。 对象字面量只能指定已知属性,而“SetStateAction”类型中不存在“alertRules”。ts(2345)
【问题讨论】:
-
我想知道你为什么使用花括号
setAlertRules({ alertRules });我认为应该是setAlertRules(alertRules);因为你现在提供的对象是字段 alertRules 而不是数组 -
是的,正如@maciej Trojiniarz 所指出的,您需要删除花括号
标签: reactjs typescript react-hooks tsx