Home > Web Front-end > Front-end Q&A > What to do if react array changes are not updated

What to do if react array changes are not updated

藏色散人
Release: 2022-12-29 10:59:07
Original
3285 people have browsed it

React array changes are not updated because array assignments in js are passed by reference. The solution is: 1. Open the corresponding react file; 2. Use the spread operator to create a new array and change the memory. Quote; 3. Use "panes.push({key: panes.length,tab: `${panes.length 1}`})" to reassign the value.

What to do if react array changes are not updated

The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.

What should I do if the react array changes but does not update?

When the attribute of an element of a state array in react changes, the setState page is not updated

During the process of writing code, you will find that if you directly use push and other methods to change the state, it stands to reason In other words, push will change the original array, and the array should be updated, but the rendered state will not change.

The problem I encountered today is: after modifying the array elements in the component, the data changed but the page was not re-rendered

This is because the component failed to recognize the changes in the array, so the page did not Re-rendering

So as long as the component senses that you have changed, you can achieve the refresh effect

Reason:

This is due to the js , the assignment of the array is passed by reference. array.push is equivalent to directly changing the memory block corresponding to the array, but the memory of the array used for comparison within react has not changed and points to the same memory. setState only does shallow compare. Therefore re-render is not triggered.

You can use the spread operator to create a new array and change the memory reference

Requirements:

What to do if react array changes are not updated

Solution:Reassignment after deconstruction

const onClick = (key) => {// tab点击函数
    if (key === 'addTab') {
      panes.push({
        key: panes.length,
        tab: `筛选记录${panes.length + 1}`
      })
      setPanes([...panes])
    }
  }
Copy after login

Recommended learning: "react video tutorial"

The above is the detailed content of What to do if react array changes are not updated. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template