简体   繁体   English

基于另一个状态道具的 Onchange 更改组件状态道具

[英]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).我有一个状态道具,它根据用户输入的输入值(数量)而变化(称之为 firstState.a)。 my question is how to change another state prop(fee, secondState.b) based on that value entered.我的问题是如何根据输入的值更改另一个状态 prop(fee, secondState.b)。 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.我以为我可以通过让 firstState.a 成为在它发生变化时触发 useEffect 的依赖项,有条件地 setState 在 UseEffect 中的 secondState 。 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.我认为这是您需要使用它的方式,当数量发生变化时,useEffect 将被触发,如果数量发生任何变化,它也会更新费用。 Or you can also make it work with onChange by setting the second state as well when you update the first state.或者您也可以通过在更新第一个状态时设置第二个状态来使其与 onChange 一起使用。

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):挂载后运行的第一个效果,让我们触发stateA更改(理想情况下不是这种情况,但为了示例而将其保留在这里 - 也许它来自 API 调用,这可能会在用户的onchange事件上触发,例如输入字段):

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:一旦stateA根据依赖数组及其值发生更改,将触发第二个效果,您可以使用首选值调用setStateB

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 .Using the Effect Hook的文档中有很好的进一步解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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