Home > Web Front-end > Front-end Q&A > What should I do if usestate in react does not render when changing its value?

What should I do if usestate in react does not render when changing its value?

WBOY
Release: 2022-04-29 17:48:59
Original
2852 people have browsed it

Method: 1. Use "const [arr, setArr]=useState([change value])" to modify the State value; 2. Create a new array and assign the value of the original array to the new array. And use "setState (new array)" to modify the State and change the address pointed to by the original array in the stack.

What should I do if usestate in react does not render when changing its value?

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

What should I do if usestate in react does not render when the value changes?

The default shallow monitoring in React is that when the State value is an object, the reference (address) of the object is stored in the stack, and what is changed by setState is Data in the heap

So after setArr(arr), the address in the stack is still the original address. React detects that the address has not changed, so it thinks that the State has not changed, so it does not re-render the page

Solution

Idea: Change the address pointed to by the original arr in the stack

The example is as follows:

1) Directly setState (the value to be modified)

const [arr, setArr] = useState([])
setArr(1)
Copy after login

2) Create a new array newArr, assign the value of the original array to the new array, and setState(newArr)

const [arr, setArr] = useState([])
const newArr = arr.slice(1)
setArr(newArr)
Copy after login

Use ES6 The expansion character

const [arr, setArr] = useState([])
setArr([...arr])
Copy after login

Recommended learning: "react video tutorial"

The above is the detailed content of What should I do if usestate in react does not render when changing its value?. 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