反应useState挂钩错误:类型'xxx'的参数不能分配给类型'SetStateAction <xx>'的参数

时间:2019-11-05 11:00:27

标签: reactjs typescript react-hooks tsx

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

  

类型'{alertRules:any; }”不可分配给“ SetStateAction”类型的参数。     对象文字只能指定已知的属性,而'alertRules'在'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);

错误是在设置状态时

  

类型'{alertRules:any; }”不可分配给“ SetStateAction”类型的参数。     对象文字只能指定已知的属性,而'alertRules'在'SetStateAction'类型中不存在。ts(2345)

1 个答案:

答案 0 :(得分:0)

简短答案:-从setAlertRules语句中删除大括号,因为这会导致init() { let appearance = UINavigationBarAppearance() appearance.shadowColor = .clear UINavigationBar.appearance().standardAppearance = appearance UINavigationBar.appearance().scrollEdgeAppearance = appearance } 的{​​{1}}和定义及其用法之间不一致。

这是ES6的功能,称为 对象文字简写

在定义 alertRules 时, setAlertRules 的类型为 SetStateAction 。并且您尝试为其赋予类型 {alertRules:any} 的值,这会导致错误。

传递给console.log("starting"); var start = process.hrtime(); console.log("start"); console.log(start); setTimeout(function(){ console.log("HELLO"); var end = process.hrtime(start); // end[0] is in seconds, end[1] is in nanoseconds const timeInMs = (end[0]* 1000000000 + end[1]) / 1000000; // convert first to ns then to ms console.log("timeInMs:", timeInMs); }, 1000); 的值是一个带有键type的对象,其值作为类型setAlertRules的数组。

因此,请删除大括号,因为它已被转换为这样的东西

alertRules

尝试使用此代码来更新alertRules。

alertRules