reactjs - TypeError:使用“useRef”时无法读取未定义的属性“onMonthSelect”
问题描述
我正在尝试在我的反应功能组件中使用 useRef,但是当我尝试访问它时,我收到错误 "TypeError: Cannot read property 'onMonthSelect' of undefined while using "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 值不会在初始渲染时设置。在访问上使用保护子句或可选链接运算符。
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: () => {},
});
推荐阅读
- java - 像 Scala 这样的 Java 静态工厂类
- meteor - 在不重新部署代码的情况下禁用旧 Meteor 服务器上的电子邮件发送
- r - 如何在 R 中跟踪 URL
- reactjs - 将函数和道具传递给另一个组件但未定义
- c - 串行控制台通信如何在微控制器中工作?
- javascript - 将 HTTP 链接添加到 SSL HTTPS 页面而不会导致混合内容“不安全”错误
- python - Python matplotlib如何显示更多刻度
- python - BeautifulSoup - AttributeError:“NoneType”对象没有属性“findAll”
- oxyplot - oxyplot 条出现故障,顺序问题
- python - Pandas 按范围分组