簡體   English   中英

TypeError:使用“useRef”時無法讀取未定義的屬性“onMonthSelect”

[英]TypeError: Cannot read property 'onMonthSelect' of undefined while using "useRef"

我正在嘗試在我的反應功能組件中使用 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;

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.format("M")
  );
}, [createdAt]);

它也可能有助於提供定義的初始參考值。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM