Home>Article>Web Front-end> 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
WBOY Original
2022-04-29 17:48:59 2769browse

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)

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)

Use ES6 The expansion character

const [arr, setArr] = useState([]) setArr([...arr])

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!

Statement:
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