微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

类型错误:使用“useRef”时无法读取未定义的属性“onMonthSelect”

如何解决类型错误:使用“useRef”时无法读取未定义的属性“onMonthSelect”

我正在尝试在我的反应功能组件中使用 useRef,但是当我尝试访问它时出现错误 “类型错误:在使用“useRef”时无法读取未定义的属性“onMonthSelect”。

这是下面的代码

import React,{ useRef,useState,useEffect } from "react";
import moment from "moment";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";
import { SingleDatePicker } from "react-dates";

const SingleDatePickerComponent = () => {
  const monthController = useRef();
  const [createdAt,setCreatedAt] = useState(moment());

  const onDateChange = (createdAt) => {
    console.log(createdAt);
    setCreatedAt(createdAt);
  };

  useEffect(() => {
    console.log(monthController);
    // Todo: check if month is visible before moving
    monthController.current.onMonthSelect(
      monthController.current.month,createdAt.format("M")
    );
//In this useEffect i am getting the error
  },[createdAt]);

  return (
    <div>
      <div style={{ marginLeft: "200px" }}>
      </div>
      <SingleDatePicker
        date={createdAt}
        startDateId="MyDatePicker"
        onDateChange={onDateChange}
        renderMonthElement={(...args) => {
          // console.log(args)
          monthController.current = {
            month: args[0].month,onMonthSelect: args[0].onMonthSelect,};
          // console.log(monthController)
          return args[0].month.format("MMMM");
        }}
        id="SDP"
      />
    </div>
  );
};

export default SingleDatePickerComponent;

解决方法

尚未在初始渲染中设置 ref 值。在访问中使用保护子句或可选链运算符。

useEffect(() => {
  // TODO: check if month is visible before moving
  monthController.current && monthController.current.onMonthSelect(
    monthController.current.month,createdAt.format("M")
  );
},[createdAt]);

useEffect(() => {
  // TODO: check if month is visible before moving
  monthController.current?.onMonthSelect(
    monthController.current.month,[createdAt]);

提供定义的初始引用值也可能有帮助。

const monthController = useRef({
  onMonthSelect: () => {},});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。