Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

javascript - How to handle nested useState in hooks just like the nested setState in component based in react?

I am migrating a react app from component to functional with hooks. The problem I'm facing is that we have a nested setState using callbacks. useState doesn't have this feature. I know I could use useEffect but there are functions that fire different functions depending on who triggered the change of a single state like the ones below. These can be isolated using the callback of setState but I'm wondering how to convert such using hooks. The only thing I have in mind is nesting a useEffect which is a bad idea based on the docs, you shouldn't loop/nest hooks.

setState({
   state1: "",
   state2: "",
}, () => {
    setState({
       state3: ""
    }, () => {
       function 1
    })
})

setState({
   state1: "",
   state2: "",
}, () => {
    setState({
       state3: ""
    }, () => {
       function 2
    })
})
question from:https://stackoverflow.com/questions/65877606/how-to-handle-nested-usestate-in-hooks-just-like-the-nested-setstate-in-componen

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You probably can do something like this, I'm not sure if that's the best way to do

useEffect(() => {
  setState1;
  setState2
}, [])

useEffect(() => {
// you will need some logic here to prevent inital run
// like say if state1 and state2 is at inital state, don't set state3
  setState3;
}, [state1, state2])

useEffect(() => {
// same idea, you will need logic from state3 to prevent inital run
  func1
}, [state3])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...