我可以更新异径钩内的外部状态吗?

时间:2019-09-12 16:31:08

标签: reactjs

我正在做一个带有进度倒计时条的滑块,每10s滑块会显示下一张图像。基本上,问题是我需要在每次启动调度时将时间设置为10s

此刻保持相同的秒数,因此,如果您等待3秒9,8,7,然后单击“下一步”,它将显示下一张图像,但是时间从7开始,我需要设置调用reduces的时间

我的问题是在调用reducer时如何调用setCount?

const initialState = {scene: 0};

function reducer(state, action) {

    switch (action.type) {
      case 'next':        
        //setCount()====> 'setCount' is not defined
        return {scene: state.scene + 1};
      case 'prev':
        return {scene: state.scene - 1};
      default:
        throw new Error();
    }
}


function App() {
    const limitSlider = 17
    const initialCount = 10
    const [state, dispatch] = useReducer(reducer, initialState);
    const [currentCount, setCount] = useState(initialCount);



    useEffect(
        () =>{
            const timer = () => setCount(currentCount - 1);

            if (currentCount <= 0) {

                //stop countdown 
                if ( state.scene === limitSlider) return

                //change to the next scene
                dispatch( {type: 'next'} )

                //set count
                setCount(10)
                return;
            }

            //reset interval
            const id = setInterval(timer, 1000);
            return () => clearInterval(id);
    },[currentCount, state.scene])


    return (
        <>



                scene: {state.scene} time: {currentCount}

                <button onClick={() => dispatch({type: 'prev' })} disabled={state.scene === 0}>-</button>
                <progress max="" value={`${currentCount}%`}> </progress> // progress is not working need to figure it out first the seconds
                <button onClick={() => dispatch({type: 'next'})} disabled={state.scene === limitSlider}>+</button>


        </>
  );
}

对不起,我尝试使用stackoverflow中的预构建代码段进行编译,但出现了一些错误

2 个答案:

答案 0 :(得分:1)

您可以将所有状态放入单个化简器中:

const initialState = {
  scene: 0,
  count: 10
};

function reducer(state, action) {
  switch (action.type) {
    case "next":
      return { scene: state.scene + 1, count: 10 };
    case "prev":
      return { scene: state.scene - 1, count: 10 };
    case "inc":
      return { ...state, count: state.count + 1 };  
    case "dec":
      return { ...state, count: state.count - 1 };           
    default:
      throw new Error();
  }
}

在此处填写代码:make this work

答案 1 :(得分:0)

我只是通过在onclick内使用setcount()来解决问题的,不知道这是在简化器之后还是在另外的方法中调用它

<button onClick={() => {
                    setCount(initialCount);
                    dispatch({type: 'prev' })
                }} disabled={state.scene === 0}>-</button>

                <progress max="1%" value={`${currentCount}%`}> </progress>

                <button onClick={() => {
                    setCount(initialCount);
                    dispatch({type: 'next'})}} disabled={state.scene === lastScene}>+</button>