简体   繁体   中英

Changing a component state prop based on a Onchange of another state prop

I have a state prop that changes based on the input value(amount) the user enters(call it firstState.a). my question is how to change another state prop(fee, secondState.b) based on that value entered. I thought I could conditionally setState of the secondState in a UseEffect by having the firstState.a be the dependency which fires the useEffect whenever it changes. What am I not understanding.

pseudo code

useEffect(()=>{
  if(...) {
    setSecondState(secondstate.b)
  } else { 
    setSecondState(secondstate.b)
  }
}, [firstState.a])

I think this is the way that you need to use it, when the amount changes, the useeffect will be fired and if theres any change in the amount, it will update the fee as well. Or you can also make it work with onChange by setting the second state as well when you update the first state.

useEffect(() => {
        setFee(amount)

    }, [amount)])

Let's imaging you have 2 different states:

const [stateA, setStateA] = useState('');
const [stateB, setStateB] = useState('');

First effect to run after mounting, let's trigger the stateA change (ideally this is not the case but leave it here for the sake of example - maybe it's coming from an API call, this can be triggered maybe on user's onchange event for example of an input field):

useEffect(() => {
  setStateA('value');
}, []);

Second effect will be triggered once stateA changes based on the dependency array and on its value you can call setStateB with the preferred value:

useEffect(() => {
   if (stateA === 'value') {
      setStateB('first condition applied');
   } else {
      setStateB('second condition applied');
   }
}, [stateA]);

Full example of the function component's body:

const [stateA, setStateA] = useState('');
const [stateB, setStateB] = useState('');

useEffect(() => {
  setStateA('value');
}, []);

useEffect(() => {
   if (stateA === 'value') {
      setStateB('first condition applied');
   } else {
      setStateB('second condition applied');
   }
}, [stateA]);

Good further explanation in the documentation of Using the Effect Hook .

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