将类组件转换为功能组件后的问题[重复]

Posted

技术标签:

【中文标题】将类组件转换为功能组件后的问题[重复]【英文标题】:Problems after converting class component to function component [duplicate] 【发布时间】:2021-04-01 08:44:44 【问题描述】:

在我将此文件中的所有内容转换为可以使用挂钩后,我遇到了一些错误。

当我按下 calendarStrip 组件上的日期时,我收到了这个错误 "2020-12-22 is not a function

调用堆栈。告诉我问题出在 onDateSelected 上,您可以在下面的代码中找到。 这让我想知道我是否搞砸了 useStates,因为一切都在类组件中工作?

带有 USESTATE 和 CALENDARSTRIP 组件的代码

const [datesWhitelist] = useState([
    
      start: moment(),
      end: moment().add(365, "days"),
    ,
  ]);
  const [todoList] = useState([]);
  const [markedDate] = useState([]);
  const [currentDate] = useState(
    `$moment().format("YYYY")-$moment().format("MM")-$moment().format(
      "DD"
    )`
  );
  const [selectedTask] = useState(null);
  const [isDateTimePickerVisible] = useState(false);
  const [createEventAsyncRes] = useState("");

<CalendarStrip
        calendarAnimation= type: "sequence", duration: 30 
        style=
          height: 150,
          paddingTop: 20,
          paddingBottom: 20,
        
        calendarHeaderStyle= color: colors.text 
        dateNumberStyle= color: colors.text, paddingTop: 10 
        dateNameStyle= color: colors.text 
        highlightDateNumberStyle=
          color: colors.text,
          backgroundColor: "#990000",
          marginTop: 10,
          height: 35,
          width: 35,
          textAlign: "center",
          borderRadius: 17.5,
          overflow: "hidden",
          paddingTop: 6,
          fontWeight: "400",
          justifyContent: "center",
          alignItems: "center",
        
        highlightDateNameStyle= color: colors.text 
        disabledDateNameStyle= color: colors.text 
        disabledDateNumberStyle= color: colors.text 
        datesWhitelist=datesWhitelist
        iconContainer= flex: 0.1 
        markedDates=markedDate
        onDateSelected=(date) => 
          const selectedDate = `$moment(date).format("YYYY")-$moment(
            date
          ).format("MM")-$moment(date).format("DD")`;
          _updateCurrentTask(selectedDate);
          currentDate(selectedDate);
        
      />

【问题讨论】:

const [value] = useState(something); 是的,看起来你可能不明白useState 做了什么,没有setter 的useState 有点没有意义。 【参考方案1】:

这就是问题所在:

currentDate(selectedDate);

你正在使用一个字符串作为一个函数,看看你如何在状态中声明它

【讨论】:

在类组件上使用 this.setState(currentDate: selectedDate,)

以上是关于将类组件转换为功能组件后的问题[重复]的主要内容,如果未能解决你的问题,请参考以下文章

如何将类组件转换为功能组件?

如何将类组件转换为功能组件?

React将类组件转换为功能组件不起作用

将类组件转换为功能组件 TypeError: users.filter is not a function

将类重构为 React 中的功能组件

使用钩子将类组件转换为函数式