为什么在 React Hooks 中排序后数组没有更新? [英] Why is array not updating after sorting in React Hooks?

查看:67
本文介绍了为什么在 React Hooks 中排序后数组没有更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 React 的新手.状态数组在排序功能后仅更新一次.为什么第二次触发排序功能后没有再次更新?

I am new to React. The array in state is updating only once after sort function. Why is it not updated again after the sort function is triggered second time?

const [cases, setCases] = useState([1, 2, 3, 4, 5]);

let sortDown = true
let sorted = []

    function sort(){
        const copy = [...cases]
        if(sortDown){
            sorted = copy.sort(function(a, b){
                return b - a 
            })
        } else {
            sorted = copy.sort(function(a, b){
                return a - b
            })
        }
        sortDown = !sortDown
        setCases(sorted)
    }

推荐答案

React 在 props 或 state 改变时重新渲染组件.在您的情况下,您声明 sorted 数组,然后将其传递给 setCases.所以第一次 setCases 采用 sorted 数组,这是它的新值.然后再次对值进行排序,并改变 sorted 数组并将其再次传递给 setCases.但是 setCases 不会将 sorted 视为新数组,因为它已发生变异,因此引用未更改.对于 React,它仍然是您第一次传递的相同数组.您需要返回新数组,然后将其传递给 setCases.

React rerenders the component when props or state changed. In your case, you declare sorted array and then you pass it to setCases. So for the first time setCases takes sorted array and it is new value for that. Then you sort the values again and you mutate the sorted array and pass it again to setCases. But setCases doesn't consider sorted as a new array because it was mutated so the reference was not changed. For React it is still the same array you passed at first time. You need to return new array and then pass it to setCases.

您应该做的另一件事是将 sortDown 存储在 state 中.否则它将在每次渲染时重新初始化.以下代码应该适用于您的情况:

The other thing you should do is to store sortDown in state. Otherwise it will be reintialized every render. Following code should work in your case:

    const [cases, setCases] = useState([1, 2, 3, 4, 5]);
    const [sortDown, setSortDown] = useState(true)

        function sort(){
            const copy = [...cases] // create copy of cases array (new array is created each time function is called)
            if(sortDown){
                copy.sort(function(a, b){ // mutate copy array
                    return b - a 
                })
            } else {
                copy.sort(function(a, b){
                    return a - b
                })
            }
            setSortDown(!sortDown); // set new value for sortDown
            setCases(copy); // pass array to setCases
        }

这篇关于为什么在 React Hooks 中排序后数组没有更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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