[英]React using forwardRef always update child component even using memo
So I have a DatePicker ChildComponent that I need to access its ref
via forwardRef
from the Parent .所以我有一个 DatePicker ChildComponent ,我需要通过Parent的
forwardRef
访问它的ref
。 Basically everything works fine.基本上一切正常。
But there's one problem.但是有一个问题。
Each time I update something on the Parent Other ChildComponents that has no any relation with DatePickerChild , the DatePicker is still rendering even it shouldn't be.每次我在 Parent Other ChildComponents上更新与DatePickerChild没有任何关系的内容时, DatePicker 仍在呈现,即使它不应该呈现。
I tried to remove the passing of ref from parent to child then the component is not rerendering anymore each time I made an update to other components that I want to solve.我试图删除 ref 从父级到子级的传递,然后每次我对要解决的其他组件进行更新时,该组件都不再重新渲染。
<NativeDatePicker
ref={datePickerRef} // <-- When I comment this component is not rendering anymore.
currentDate={values.birthday}
onDateChange={handleBirthdayChange}
/>
I already started using callback memoization by using useCallback
to optimize but still no luck.我已经开始通过使用
useCallback
来优化回调记忆,但仍然没有运气。
Here is my code below:下面是我的代码:
DatePicker.tsx日期选择器.tsx
type Props = {
// ref: RefObject<DatePicker>;
currentDate: string | Date | undefined;
onDateChange: (newDate: string) => void;
};
const NativeDatePicker = forwardRef(
({ currentDate, onDateChange }: Props, ref: any) => {
console.log('tadah!');
return (
<DatePicker
ref={ref}
style={wrapperStyle.wrapper}
date={currentDate}
mode="date"
placeholder="select date"
format="YYYY-MM-DD"
// minDate="2016-05-01"
// maxDate={Date.now()}
confirmBtnText="Confirm"
cancelBtnText="Cancel"
customStyles={styles}
onDateChange={onDateChange}
/>
);
},
);
const MemoizedNativeDatePicker = memo(NativeDatePicker);
I would not show every code in my ParentComponent only the props and refs I'm passing into the DatePicker.我不会只显示我的ParentComponent中的每个代码我传递给 DatePicker 的 props 和 refs。
// Memoized Callback Function
const handleBirthdayChange = useCallback(
(newDate: string) => setFieldValue('birthday', newDate),
[setFieldValue],
);
const datePickerRef = createRef<DatePicker>();
const datePickerRefOnPress = () => datePickerRef.current!.onPressDate();
Am I missing something?我错过了什么吗? Thanks for any help.
谢谢你的帮助。
You are creating a ref using createRef
, which on every re-render will return you a new ref instance and hence will lead to failure in optimization of child re-render with React.memo
.您正在使用
createRef
创建一个 ref,它在每次重新渲染时都会返回一个新的 ref 实例,因此会导致使用React.memo
优化子重新渲染失败。
You should instead use useRef
hook for a functional component to create a ref您应该改为使用
useRef
钩子作为功能组件来创建 ref
const datePickerRef = useRef<DatePicker>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.