简体   繁体   English

SetInterval 每次在 React Js 中显示默认 State 值

[英]SetInterval Showing default State value every time in React Js

CurrentIndex is showing 0 every time I want to run it to custom duration or dynamic array length每次我想将 CurrentIndex 运行到自定义持续时间或动态数组长度时,它都显示 0

    Const [currentIndex, setCurrentIndex] = useState(1);

    useEffect(() => {
    setInterval(() => {
      setCurrentIndex(5);
      if (currentIndex >= 5) {
        setCurrentIndex(0);
      }
      console.log('Current Index', currentIndex);
    }, 3000);
  }, []);

React state is async so it take some time delay for update. React state 是异步的,因此更新需要一些时间延迟。 so use separate useEffect hook for listen index所以使用单独的useEffect钩子来监听索引

Const[currentIndex, setCurrentIndex] = useState(1);

useEffect(() => {
  if (currentIndex >= 5) {
    setCurrentIndex(0);
  }
  console.log('Current Index', currentIndex);
}, [currentIndex])

useEffect(() => {
  setInterval(() => {
    setCurrentIndex(5);
  }, 3000);
}, []);

You can do it like that你可以这样做

 var [currentIndex, setCurrentIndex] = useState(1); useEffect(() => { setInterval(() => { setCurrentIndex(5); if (currentIndex >= 5) { setCurrentIndex(0); } console.log("Current Index", currentIndex); }, 3000); }, [currentIndex]);

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

相关问题 在 state 和第 3 次 state 中存储值的问题没有在 React JS 中更新 - facing issue to store value in state and 3rd time state is not updating in react js 循环遍历数组并一次显示单个项目,动态持续时间,如 react js 中的 setTimeout 或 SetInterval - loop through an array and show single item at a time with dynamic time duration like setTimeout or SetInterval in react js 每次执行 function 并且我的反应 state 更改时过滤一个数组 - Filter an array every time a function is executed and my react state change 不能 append 数组(状态元素)与 setinterval()反应 - cant append array(state element) with setinterval() in react 如何在 React js 初始化时将一个 state 值传递给另一个 state - How to pass one state value to another state on initialization in react js React JS - 如何实时更新 State 数组? - React JS - How to update State Array in real time? 根据 React.js 中的 state 值切换按钮值 - Toggle button value based on state values in React.js 如何在 React.js 中将输入值添加到 state? - how can i add input value to state in React.js? 反应中的清算价值状态 - Clearing value state in react react js:如何为一次只显示一个项目的文本数组设置动画 - react js : how to animate a text array showing only one item at a time
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM