【问题标题】:React UI not updating on state changeReact UI 未在状态更改时更新
【发布时间】:2020-08-08 04:29:50
【问题描述】:

我有一个列表,需要在单击列表中的任何项目时对其重新排序。字符串数组用于绑定。用于重新排序的函数返回正确的值。但 UI 没有更新。

import React from 'react';
import ReactDOM from 'react-dom';

function swapElement(array, from, to) {
  array.splice(to, 0, array.splice(from, 1)[0])
  return array;
}

const List = props => {
  let [list, setList] = React.useState(props.item)

  const handleClick = index => {
    const items = swapElement(list, index, 0);
    console.log('UPDATED ARRAYS--------->', items)
    setList(items);
  }

  return <ul> {
    list.map((item, i) => 
      <li style={{ margin: '25px' }}
        onClick={() => handleClick(i)}
        key={i}
      >
      {item}
     </li>)
  } </ul>
}

ReactDOM.render(
  <List item={['A', 'B', 'C', 'D', 'E']} />,
  document.getElementById('root')
);

【问题讨论】:

    标签: javascript arrays reactjs


    【解决方案1】:

    UI 没有冻结,你正在改变你的状态对象并且永远不会返回一个新的数组对象引用,所以 react 不会重新渲染 UI。

    浅拷贝数组,然后变异新数组并返回。

    function swapElement(array, from, to) {
      const newArray = [...array];
      newArray.splice(to, 0, newArray.splice(from, 1)[0])
      return newArray;
    }
    

    趣事:您可以使用数组解构来交换数组的两个元素。这避免了拼接时发生的所有数组元素移位。

    function swapElement(array, from, to) {
      const arr = [...array];
      [arr[from], arr[to]] = [arr[to], arr[from]];
      return arr;
    }
    

    【讨论】:

    • 你的第二个例子太好了,可以分享!
    猜你喜欢
    • 2016-10-31
    • 2018-09-21
    • 2021-12-29
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 2020-09-28
    相关资源
    最近更新 更多