访问另一个函数内的状态值 - useState

时间:2020-12-28 12:31:34

标签: reactjs react-native

如何访问状态的更新值?我在 UI 上获取更新的值,但在动态访问状态值时却没有。

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;

更新:访问状态的正确结构是什么?是仅使用 useEffect 还是我们可以使用将返回状态的自定义钩子处理?在我的结构中看到访问单独函数中的值的困难。

1 个答案:

答案 0 :(得分:0)

请替换下面的代码并告诉我


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;