简体   繁体   中英

How can Update this state using React useState hook Button click

I try to update my react state using useState hook.

const [Combine, setCombine] = useState([{
makeTeacher:'', makeSub:''}])

*Here I hook define *

 {Teacher && Subject ?<button onClick={()=>showStatus(Teacher,Subject)}>save</button>:null }

*if Teacher and subject are available then *

 const showStatus = (t,s) => {
 setCombine( t, s)
 console.log(Combine) }

*My Desier Result is * [0] index makeTeacher:'t', makeSub:'s'

setState is asynchrone.

Do this to have updated values in the console

useEffect(()=>{
 console.log(combine) 
}, combine)
const showStatus = (t,s) => setCombine( t, s)

Currently, your console.log shows an outdated version of the 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