gpt4 book ai didi

javascript - React useRef 对于条件渲染的元素没有一致更新

转载 作者:行者123 更新时间:2023-12-03 08:09:22 26 4
gpt4 key购买 nike

在我的应用程序中,有一些用户体验逻辑需要共享。它们是由事件触发的,所以我编写了 2 个自定义钩子(Hook)。我们调用 useRefWithCalc 。另一个钩子(Hook)是更标准的useEventListener ,类似于this one .

useRefWithCalc调用 native useRef ,有一些用于 UX 的内部处理程序,然后调用 useEventListener附加这些处理程序。 useRefWithCalc返回 ref在其中创建,因此另一个组件可以使用此钩子(Hook),并获取返回的引用以附加到元素。

当引用未附加到条件渲染元素时,这对我有用。

该组件看起来像这样。请注意 2 条测试日志。

const useEventListener = (event, listener, ref) => {\
...
useEffect(() => {
...
console.log("1. ref is: ", ref.current); // test logging 1.
ref.current.addEventListener(event, listener);
return () => {
ref.current.removeEventListener(event, listener);
}
}, [event, listener, ref]);
}

const useRefWithCalc = (value) => {
const ref = useRef(null);
...
const calc = () => {
// some calculations
}
...
useEventListener(event, calc, ref)
return [ref, result]
}

// works perfectly
const WorkingElement = (props) => {
const [ref, result] = useRefWithCalc(props.value);
...
return <B ref={ref} />
}

// doesn't work consistently
const ConditionalElement = (props) => {
const [state, setState] = useState(false);
const [ref, result] = useRefWithCalc(props.value)

useEffect(()=>{
if (ref && ref.current) {
ref.current.focus();
console.log("2. ref is: ", ref.current); // test logging 2
}
}, [ref])
...
return state ? <A> : <B ref={ref} />
}

<WorkingElement />正如预期的那样工作。引用被附加,并且处理事件没有问题。

但是,在 <ConditionalElement /> ,当安装 B 时,有时测试日志记录 1 不会触发。测试记录 2 始终触发,并且裁判正确获得焦点。但这个更新并没有传递到 useEventListener

一次<B />获取 1 后续更新(例如,当用户输入某些内容时),两个日志都会正确触发,并且事件监听器会正确附加,并且其工作方式与 <WorkingElement /> 一样。


抱歉没有发布确切的代码。我觉得我的方法很复杂,而且可能是错误的。

最佳答案

在 React 中,当 ref 发生变化时,它不会触发组件更新,并且 useEffect 也不会被触发。

我建议将您的 ref 放入一个状态中,以便在 ref 更改时触发效果:

const [ref, setRef] = useState(undefined)

return (
<B ref={setRef}/>
)

关于javascript - React useRef 对于条件渲染的元素没有一致更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71275199/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com