[英]React state variable not accurate after set state in useState hook
我有一个 React function 组件与旧版 JQuery 应用程序一起运行。 When calling an event handler on a JQuery element, passing in the current React state defaults to the initial state value and not the updated state value.
已验证 x state 正在通过 useEffect 挂钩进行更改,但在调用事件侦听器时,x 设置为初始 state 值,而不是更新后的 state 值。
function MyComponent(props) {
const [x, setX] = useState(false);
// On initial render
useEffect(() => {
props.jQueryButton.addEventListener('click', onXSave)
}, [])
useEffect(() => {
console.log("x changed " + x); // everytime onXChange is called, x
state is updated with the checked value, and this console.log shows
the correct state value
}, [x]);
onXChange = event => {
setX(event.target.checked); // checked is true in this context
};
onXSave = event => {
const obj = { x: x}; // x is false here, even though the state in this context shows it to be true.
};
}
不显示错误消息。 在上面的代码中,我希望 x state 在 onXSave 方法调用中为真,但它一直显示为假。
onXSave
在初始渲染时添加为处理程序,因此x
具有当时的值。 在每次渲染时重新创建onXSave
并不重要,因为它从未使用过初始渲染。
要解决此问题,您可以将x
放入ref
unction MyComponent(props) { const [x, setX] = useState(false); const ref = useRef(); ref.current = x; // On initial render useEffect(() => { props.jQueryButton.addEventListener('click', onXSave) }, []) useEffect(() => { console.log("x changed " + x); // everytime onXChange is called, x state is updated with the checked value, and this console.log shows the correct state value }, [x]); onXChange = event => { setX(event.target.checked); // checked is true in this context }; onXSave = event => { const obj = { x: ref.current}; // by using ref, the value is always current }; }
您添加到eventListener
的onXSave
版本已过期 - 您仅在第一次渲染时添加一次,因此当x
更新并导致重新渲染时,您的 useEffect 不会再次运行,您的jQueryButton
仍将保留原来的 function,它已经关闭了一个过时的x
版本。
你需要做两件事:
useEffect
依赖数组中添加onXSave
和你的jQueryButton
作为依赖(所以当它重新渲染时,你的 function 的当前版本连接到你的 eventListener)useEffect
返回清理 function 来删除重新渲染时的旧事件侦听器。所以像:
function MyComponent(props) {
const [x, setX] = useState(false);
// On initial render
useEffect(() => {
props.jQueryButton.addEventListener('click', onXSave)
return ()=> props.jQueryButton.removeEventListener('click', onXSave)
}, [onXSave, props.jQueryButton])
useEffect(() => {
console.log("x changed " + x); // everytime onXChange is called, x
state is updated with the checked value, and this console.log shows
the correct state value
}, [x]);
onXChange = event => {
setX(event.target.checked); // checked is true in this context
};
onXSave = event => {
const obj = { x: x}; // x is false here, even though the state in this context shows it to be true.
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.