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

Dar*_*tar 7 javascript reactjs react-hooks

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

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)
    }

Run Code Online (Sandbox Code Playgroud)

小智 14

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

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

    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
        }
Run Code Online (Sandbox Code Playgroud)


Plu*_*lum 5

您应该使用状态变量来决定排序类型。

否则每次渲染都会重新初始化。

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

  function sort() {
    const copy = [...cases];
    if (sortDown) {
      copy.sort(function(a, b) {
        return b - a;
      });
    } else {
      copy.sort(function(a, b) {
        return a - b;
      });
    }
    setSortDown((prev) => !prev);
    setCases(copy);
  }
Run Code Online (Sandbox Code Playgroud)

  • 你做了什么改变?请解释你的答案 (2认同)