Reactjs TypeError:无法读取属性';onMonthSelect';使用“未定义”时的;useRef";

Reactjs TypeError:无法读取属性';onMonthSelect';使用“未定义”时的;useRef";,reactjs,use-ref,react-dates,Reactjs,Use Ref,React Dates,我试图在我的react函数组件中使用useRef,但当我试图访问它时,我得到了一个错误 TypeError:使用“useRef”时无法读取未定义的属性“onMonthSelect” 这是下面的代码 import React, { useRef, useState, useEffect } from "react"; import moment from "moment"; import "react-dates/initialize";

我试图在我的react函数组件中使用useRef,但当我试图访问它时,我得到了一个错误 TypeError:使用“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;
import React,{useRef,useState,useffect}来自“React”;
从“时刻”中导入时刻;
导入“反应日期/初始化”;
导入“react dates/lib/css/_datepicker.css”;
从“反应日期”导入{SingleDatePicker};
常量SingleDatePickerComponent=()=>{
const monthController=useRef();
const[createdAt,setCreatedAt]=useState(矩());
const onDateChange=(createdAt)=>{
console.log(createdAt);
setCreatedAt(createdAt);
};
useffect(()=>{
控制台日志(monthController);
//TODO:移动前检查月份是否可见
monthController.current.onMonthSelect(
monthController.current.month,
createdAt.format(“M”)
);
//在这种情况下,我得到了错误
},[createdAt]);
返回(
{
//console.log(args)
monthController.current={
月份:args[0]。月份,
onMonthSelect:参数[0]。onMonthSelect,
};
//控制台日志(monthController)
返回参数[0].month.format(“MMMM”);
}}
id=“SDP”
/>
);
};
导出默认SingleDatePickerComponent;

在初始渲染时还不会设置ref值。在访问上使用guard子句或可选的链接运算符

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

它还可以帮助提供定义的初始参考值

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