简体   繁体   English

在另一个 function 中访问 state 值 - useState

[英]Access state value inside another function - useState

How can I access the updated value of the state?如何访问 state 的更新值? I am getting updated values on UI but not while accessing state value on the fly.我在 UI 上获得了更新的值,但在动态访问 state 值时没有。

const OTP = () => {

  const [counter, setCounter] = useState(3);
  const [someState, setSomeState] = useState("something");

  useEffect(() => {
    startCountdownTimer();
  }, []);

  const countdownTimerFunc = () => {
    let value = counter; // <--- initial value always
    // someState <--- initial value always
    console.log('==== countdown: START====', counter); 
    if (value && value > 0) {
        setCounter(prev => prev - 1); // Updating right value
    } else {
      console.log('==== countdown: STOP====');
    }
  };

  const startCountdownTimer = () => {
    setSomeState("updated something");
    internalID = BackgroundTimer.setInterval(() => {
      countdownTimerFunc();
    }, 1000);
  };

  const counterUI = () => {
      return (
          <Text>{counter}</Text>
      )
  }

  ...

  return (
     <View>
       {counterUI()}
     </View>
  )
};

export default OTP;

Update: What is the right structure to access the state?更新:访问 state 的正确结构是什么? Is it only with useEffect or can we handle with custom hook which will return state?是仅使用 useEffect 还是我们可以使用将返回 state 的自定义钩子处理? The difficulty which am seeing in my structure to access the value inside seperate functions.在我的结构中看到访问单独函数中的值的困难。

Please replace below code and let me know请替换以下代码并告诉我


const OTP = () => {

  const [counter, setCounter] = useState(3);
  const [someState, setSomeState] = useState("something");

  useEffect(() => {
    if (counter > 0) {
      countdownTimerFunc()
    }else{
      startCountdownTimer();
    }

  }, [counter]);

  const countdownTimerFunc = () => {
    let value = counter; // <--- initial value always
    // someState <--- initial value always
    console.log('==== countdown: START====', counter);
    if (value && value > 0) {
      setCounter(counter - 1); // Updating right value
    } else {
      console.log('==== countdown: STOP====');
    }
  };

  const startCountdownTimer = () => {
    setSomeState("updated something");
    setTimeout(() => {
      countdownTimerFunc();
    }, 1000);
  };

  const counterUI = () => {
    return (
      <Text>{counter}</Text>
    )
  }

  ...

return (
  <View>
    {counterUI()}
  </View>
)
};

export default OTP;

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

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