为什么反应进度条会渲染整个百分比而不是逐渐增加?

时间:2019-02-07 23:43:42

标签: javascript reactjs

我正在尝试根据页面加载时setTimeout的变化来更新百分比状态,因此填充符将将ProgressiveBar填充至100%

const { React, ReactDOM } = window
const { useEffect, useState, Fragment } = React
const { render } = ReactDOM
const rootNode = document.getElementById('app')

const ProgressiveBar = () => {
   const [state, setState] = useState({
    percentage : 10
   });


   if(state.percentage < 100 ) {
         setTimeout(
       setState(prevState => {

         let { percentage } = prevState;
         percentage = prevState + 1; 
         return {
           percentage
         }
       }), 30
     )
   }

  return (
    <div >
      <h4>progressive bar when......
      </h4>
       <div className="progressiveBar">
         <div className="innerFiller" style={{width:`${ state.percentage }%`}}>
         </div>
        </div>
       <div>
      </div>
      </div>
  )
}


ReactDOM.render(<ProgressiveBar/>, rootNode)

1 个答案:

答案 0 :(得分:0)

类似的事情可能会起作用

const ProgressiveBar = () => {
  const [percentage, setPercentage] = useState(10);

  if (percentage < 100) {
    setTimeout(() => setPercentage(percentage + 1), 30);
  }

  return (
    <div>
      <h4>progressive bar when......</h4>
      <div className="progressiveBar">
        <div className="innerFiller" style={{ width: `${percentage}%` }}>
          {percentage}
        </div>
      </div>
      <div />
    </div>
  );
};