简体   繁体   中英

not getting updated state value in react using hooks?

I am using functional components .I have 2 radio buttons and a submit button.On submit button I am not able to get updated value .

here is my code https://codesandbox.io/s/peaceful-microservice-ywdoe?file=/src/App.js

step to reproduce

  1. run the application.BY default radio button value is no
  2. Change any of radio button to yes .then click submit button.it should show updated value of state. but it is showing initial state why ??

button submit handler

 const buttonHandler = useCallback(async e => {
    e.preventDefault();
    console.log(state);
  }, []);

if change blank array to one item in array state like this .it works correctly, but it re-render button component when I change the state . any better solution ??? to prevent re-rendering and get updated state?

 const buttonHandler = useCallback(async e => {
    e.preventDefault();
    console.log(state);
  }, [state]);

Add state to the buttonHandler useCallback dependency array.

const buttonHandler = useCallback(async e => {
  e.preventDefault();
  console.log(state);
}, [state]);

编辑 nifty-tree-5yrxq

Alternatively, don't memoize the buttonHandler callback.

const buttonHandler = e => {
  e.preventDefault();
  console.log(state);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM