我如何在React的while循环内更​​新State [英] How do I update State inside of a while loop in React

查看:76
本文介绍了我如何在React的while循环内更​​新State的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这个代码.

var s = [1,2,3,4,5,6,7,8,9,0];
const[arr,setArr]=useState(s);
while(arr.length != 0){
    setArr(arr.splice(0,1));
    console.log(arr); //This returns [2,3,4,5,6,7,8,9,0] and [3,4,5,6,7,8,9,0] and so on until []
}

我在functionanl组件的末尾返回{arr.length}.但是,它首先渲染10,然后等待直到整个while循环运行,然后渲染1.所有中间的数字都将被跳过.

I return {arr.length} at the end of the functionanl component. However, it first renders 10, and waits till the whole while loop is run and then renders 1. All the numbers inbettween are simply skipped.

我有点理解为什么会发生这种情况,但是无论如何我可以显示所有长度吗?我有一个睡眠功能,该功能需要花费毫秒并在该时间暂停该程序,以确保用户可以在合理的时间内看到渲染的长度.

I kind of understand why this happens, but is there anyway I can show all the lengths? I have a sleep function that takes milliseconds and halts the program for that time, if it is of any use in order to make sure the user can see the rendered lengths for a reasonable time.

提前谢谢!

推荐答案

假设这是一个功能组件(我猜你是在 useState 而不是 setState const [arr,setArr] = setState(s); ),您需要让组件在设置下一个状态之前呈现每个状态.否则,所有状态更新将被批处理在一起,并且只有在完成所有操作后,组件才会再次呈现.

Assuming this is a functional component (I'm guessing you meant useState, not setState, in const[arr,setArr]=setState(s);), you need to let the component render each state before setting the next. Otherwise, all the state updates get batched together and the component only renders again when they're all done.

例如:

function Example() {
    const [arr, setArr] = useState([1,2,3,4,5,6,7,8,9,0]);
    // Set up a timer on mount, remove it on dismount and when
    // we run out of values to show
    useEffect(() => {
        const handle = setInterval(() => {
            // Note useing the callback function, so `arr` isn't stale
            // in this callback
            setArr(a => {
                if (a.length) {
                    // Update the array, dropping the first entry
                    return a.slice(1);
                }
                // No more entries, stop the timer
                clearInterval(handle);
                return a;
            });
        }, 500);
        return () => clearInterval(handle);
    }, []);
    return <div>{arr.join()}</div>;
}

这篇关于我如何在React的while循环内更​​新State的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆