我试图在我的react函数组件中使用useRef,但当我试图访问它时,我遇到了错误"TypeError:使用"时无法读取未定义的属性"onMonthSelect";useRef"&"。
下面是这个的代码
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值。在访问上使用guard子句或Optional Chaining运算符。
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]);
它还可以帮助提供定义的初始ref值。
const monthController = useRef({
onMonthSelect: () => {},
});