英文:
why variable value is not updated inside function . in react js?
问题
I am sending a function as props in reactjs. I have one state "form submitted" or "not submitted". I am getting wrong output (console output) inside the function. don't know why? But outside function, I am getting the correct value.
here is my code: Link to CodeSandbox
const NestedComponent = () => {
const { registerState, formState } = useHookFormContext();
console.log(formState.isSubmitted, "outside");
return (
<>
<CustomApi
key="abc"
options={[]}
onChange={() => {
console.log(formState.isSubmitted, "inside");
console.log("sss");
}}
/>
</>
);
};
Steps to reproduce the bug:
- Run the application. See the console; it will show false, which is correct.
- Click the submit button. See the console; it will show true, which is correct.
- Now change the dropdown value. See the console; it will show false value, which is incorrect. Why is it showing a different value?
Is it a closure issue?
英文:
I am sending a function as props in reactjs .I have one state "form submitted" or "not submitted". I am getting wrong output (console output) inside the function . don't know why ? But outside function I am getting correct value.
here is my code
https://codesandbox.io/s/cool-dawn-0uu62q?file=/src/nested.tsx
const NestedComponent = () => {
const { registerState, formState } = useHookFormContext();
console.log(formState.isSubmitted, "outside");
return (
<>
<CustomApi
key={"abc"}
options={[]}
onChange={() => {
console.log(formState.isSubmitted, "inside");
console.log("sss");
}}
/>
</>
);
};
steps to reproduce bug
- run application . see console it will show false which is correct.
- Click submit button . see console it will show true which is correct.
- Now change the dropdown value .see console it will show false value which is incorrect correct. why is showing different value
is it closure issue ???
答案1
得分: 0
以下是翻译好的部分:
这个版本的mui-react-hook-form-plus已经修复了问题 - v1.3.5
忘记在每个渲染周期重新分配onChangeRef
。因此,闭包获取了之前的值
+ const onChangeRef = React.useRef(onChange);
+ /**
+ * 我们在每次渲染时更新引用
+ */
+ onChangeRef.current = onChange;
示例:https://codesandbox.io/s/quizzical-nova-ur0rv8?file=/src/nested.tsx
英文:
Fixed with this release of mui-react-hook-form-plus - v1.3.5
Forgot to reassign the onChangeRef
in each render cycle. Hence closure got the prev value
+ const onChangeRef = React.useRef(onChange);
+ /**
+ * we update the ref on every render
+ */
+ onChangeRef.current = onChange;
example: https://codesandbox.io/s/quizzical-nova-ur0rv8?file=/src/nested.tsx
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论