简体   繁体   中英

Using setState of functional component inside a new Promise?

I know that setting state is async, but is there a use case for setting a state inside a new promise? I do not understand promises to be honest, they are difficult to understand and their use cases baffle me. But I know that sometimes I setState and I console.log it and it's undefined. I wanna go around that by putting it into a new Promise. Is this a correct approach? In terms of my code snippet, how would I even structure that logic? I don't know what the if would be checking for.

 onRowClicked={row=>{ const trial = new Promise((resolve,reject)=>{ let setter = setRowIndex(row.index) if(setter) { resolve() } else { reject(); } })

you want to print updated state, to accomplish that it depends how you are using react.

  • class component: you can print this.state at componentDidUpdate lifecycle method. Alternatively, at this.setState function you can pass a second argument, a function that runs after this.state is updated;

  • hooks: use useEffect to run on state updates like: useEffect(() => console.log(myState) ,[myState])

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