React函数组件移除功能异常:点击移除无即时重渲染
Hey there! Let's break down what's going on with your React component. The issue boils down to how React detects state changes and the importance of immutability when updating state.
The Root Cause
In your remove function, you're doing two things that trip up React:
- You're directly mutating the existing state array with
list.pop()— this changes the original array in place instead of creating a new one. - You then call
setList(list)and pass the same array reference back to state.
React uses a shallow comparison to determine if state has changed. Since the array reference is the same (even though its contents are different), React thinks nothing has changed and skips re-rendering the component.
On the flip side, your add function works because you're creating a brand new array with [list.length, ...list] — this gives state a new reference, so React picks up the change and re-renders immediately.
The Fix
You need to avoid mutating the original state and instead pass a new array to setList. Here are two clean ways to do this:
Option 1: Use slice() to create a new array without the last element
const remove = () => { // slice(0, -1) returns a new array with all elements except the last one setList(list.slice(0, -1)); }
Option 2: Spread the array into a new one, then modify the copy
const remove = () => { // Create a copy of the original array const newList = [...list]; // Modify the copy instead of the original newList.pop(); // Update state with the new array reference setList(newList); }
Either approach will ensure you're passing a new array reference to setList, which React will recognize as a state change and trigger an immediate re-render. You'll also notice your useEffect hook will log the updated list every time you click remove now, since the state reference has changed.
内容的提问来源于stack exchange,提问作者Hristo Todorov

