admin管理员组

文章数量:1290984

I have a list and need to reorder list it on clicking any item on the list. Array of string are used for binding. The function that used for reordering is returning the correct value. But the UI is not updating.

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')
);

I have a list and need to reorder list it on clicking any item on the list. Array of string are used for binding. The function that used for reordering is returning the correct value. But the UI is not updating.

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')
);
Share Improve this question edited Aug 8, 2020 at 9:51 Siva Kondapi Venkata 11k2 gold badges19 silver badges31 bronze badges asked Aug 8, 2020 at 4:29 J. RayhanJ. Rayhan 1112 silver badges4 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 11

The UI isn't freezing, you are mutating your state object and never returning a new array object reference, so react isn't re-rendering the UI.

Shallow copy the array, then mutate new array and return.

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

Fun fact: You can use array destructuring to swap two elements of an array. This avoids all the array element shifting that occurs with the splicing.

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

本文标签: javascriptReact UI not updating on state changeStack Overflow