Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[react] 数组用useState做状态管理的时候,使用push,pop,splice等直接更改数组对象,会引起页面渲染吗?【热度: 488】 #464

Open
yanlele opened this issue Jun 21, 2023 · 0 comments
Labels
web框架 web 框架相关知识 快手 公司标签
Milestone

Comments

@yanlele
Copy link
Member

yanlele commented Jun 21, 2023

关键词:useState状态管理、push 直接更改数组对象、pop 直接更改数组对象、splice 直接更改数组对象

在React中,使用useState时使用pushpopsplice等直接更改数组对象是不推荐的做法,因为这种直接更改数组的方式会改变原始状态,React不会检测到这种状态变化,从而无法正确地渲染页面。因此,在React中更新数组状态的正确方式是创建一个新的数组对象,然后使用set函数来更新状态,这样React就能够正确地检测到状态变化,并重新渲染页面。

例如,在使用useState管理数组状态时,如果想要向数组中添加一个新元素,可以使用以下方式:

const [list, setList] = useState([]);

function handleAdd() {
  // 创建一个新的数组对象
  const newList = [...list];
  // 向新数组中添加新元素
  newList.push('new item');
  // 更新状态
  setList(newList);
}

在这个例子中,我们首先创建了一个新的数组对象newList,然后向这个新数组中添加新元素,最后使用setList函数更新状态。这样,React就能够正确地检测到状态变化,并重新渲染页面。

@yanlele yanlele added web框架 web 框架相关知识 快手 公司标签 labels Jun 21, 2023
@yanlele yanlele added this to the milestone Jun 21, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
web框架 web 框架相关知识 快手 公司标签
Projects
None yet
Development

No branches or pull requests

1 participant