【问题标题】:Changing a component state prop based on a Onchange of another state prop根据另一个状态道具的 Onchange 更改组件状态道具
【发布时间】:2020-12-21 15:51:51
【问题描述】:

我有一个 state prop,它会根据用户输入的输入值(数量)而变化(称为 firstState.a)。我的问题是如何根据输入的值更改另一个 state prop(fee, secondState.b)。我想我可以通过让 firstState.a 成为在 useEffect 发生变化时触发 useEffect 的依赖项,从而有条件地在 UseEffect 中设置 secondState 的状态。我不明白什么。

伪代码

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

【问题讨论】:

    标签: javascript reactjs react-hooks jsx


    【解决方案1】:

    我认为这是您需要使用它的方式,当金额发生变化时,将触发使用效果,如果金额有任何变化,它也会更新费用。或者,您也可以通过在更新第一个状态时设置第二个状态来使其与 onChange 一起使用。

    useEffect(() => {
            setFee(amount)
    
        }, [amount)])
    

    【讨论】:

    • 你可以通过在里面加入 if 语句来进一步改进它。
    【解决方案2】:

    让我们想象一下你有两种不同的状态:

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

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

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

    一旦stateA 基于依赖数组及其值发生更改,将触发第二个效果,您可以使用首选值调用setStateB

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

    函数组件主体的完整示例:

    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]);
    

    Using the Effect Hook 的文档中有很好的进一步解释。

    【讨论】:

      猜你喜欢
      • 2018-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-20
      • 2021-12-14
      • 2019-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多