【问题标题】:React useState hooks error: Argument of type 'xxx' is not assignable to parameter of type 'SetStateAction<xx>'React useState 挂钩错误:“xxx”类型的参数不可分配给“SetStateAction<xx>”类型的参数
【发布时间】: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


【解决方案1】:

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

这是 ES6 的特性,称为 Object literal Shorthand

在定义 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 ); 

【讨论】:

    猜你喜欢
    • 2022-11-12
    • 2021-07-21
    • 2021-12-30
    • 2021-03-08
    • 2021-08-01
    • 2020-04-17
    • 1970-01-01
    • 2021-10-03
    • 2021-06-26
    相关资源
    最近更新 更多