且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么在 React Hooks 中排序后数组没有更新?

更新时间:2022-12-16 18:47:18

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
        }