【发布时间】:2020-02-22 00:55:28
【问题描述】:
我有一个与旧版 JQuery 应用程序一起运行的 React 函数组件。在 JQuery 元素上调用事件处理程序时,传入当前 React 状态默认为初始状态值,而不是更新后的状态值。
通过 useEffect 钩子验证 x 状态正在改变,但是在调用事件监听器时,x 被设置为初始状态值,而不是更新后的状态值。
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 状态在 onXSave 方法调用中为 true,但它一直显示为 false。
【问题讨论】:
标签: javascript reactjs