繁体   English   中英

React 功能组件 state 未更新

[英]React functional component state is not updating

尽管更改文本 state 可以正常工作,但我无法更新togglelight灯 state。

export default function CardImageExample (props) {

  const [text,setext] = React.useState("Open Gate")
  const [togglelight,setogglelight] = React.useState(props.data.light)

  function change(){
    setext("Gate Opened")
    db.ref('/Door').set({mainDoor : 'opened' })
    setTimeout(function(){setext("Open Gate")}, 1300)
  }

  function ToggleLights(){
    console.log("before toggle",togglelight)

    if(togglelight)
    setogglelight(false)

    else
      setogglelight(true)

    console.log("after toggle",togglelight)
  }

  return (
    <View style={{alignItems: 'center'}}>
      <Content>
        <Button rounded style={styles.button} onPress={change} >
          <Text style={styles.text}> {text} </Text>
        </Button>

        <Text>{'\n\n'}</Text>

        <ToggleSwitch
          isOn={togglelight}
          onColor="yellow"
          offColor="grey"
          label="Lights  "
          labelStyle={styles.text}
          size="medium"
          onToggle={ToggleLights}
        />


      </Content>
    </View>
  );
}


我没有返回 function 因为代码的 rest 工作正常......只是 state 没有更新

您需要使用回调参数调用setogglelight()才能正确访问之前的切换togglelight

尝试如下:

function ToggleLights() {
   setogglelight(prevLight => !prevLight);
}

我希望这有帮助!

更改 state 是异步的 function

尝试将您的 function 更改为此

  async function ToggleLights(){
      console.log("before toggle",togglelight)

      if(togglelight)
          await setogglelight(false)

      else
          await setogglelight(true)

      console.log("after toggle",togglelight)
  }

希望这可以帮助

暂无
暂无

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

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