React useState hooks error: Argument of type 'xxx' is not assignable to parameter of type 'SetStateAction<xx>'

React useState hooks error: Argument of type 'xxx' is not assignable to parameter of type 'SetStateAction<xx>'

我使用 React hooks 更新,但是在 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 语句中删除花括号,因为它导致 typesetAlertRules 在定义及其用法。

这是 ES6 的特性,称为 对象文字 Shorthand

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

传递给alertRules的值是一个对象,键为alertRules,其值为Alert类型的数组。

所以,删除大括号,因为它被转换成这样

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

尝试使用此代码更新 alertRules。

// see no curly braces .
 setAlertRules( alertRules );