[英]Does changing state cause re-render in ReactJS
In my ReactJS application, I have an array of dictionaries stored as a state called items that looks like this:在我的 ReactJS 应用程序中,我有一个字典数组存储为 state 称为项目,如下所示:
this.state = {
items: []
}
I then add items to the list after certain events, ex: click a button, which causes this.state.items to continue to grow to look like something like this:然后我在某些事件之后将项目添加到列表中,例如:单击一个按钮,这会导致 this.state.items 继续增长,看起来像这样:
items: [{"item": "milk", "price": 3.00}, {"item": "eggs", "price": 5.00}]
The items state directly influences my UI because state 项目直接影响我的 UI,因为
this.state.items.map((item, i) => <><h1>{item.item}</h1><p>{item.price}</p></>)
My question is: Is this causing my UI to have to re-render items in the items list that have already been renders every time the items state changes.我的问题是:这是否会导致我的 UI 必须在每次项目 state 更改时重新渲染项目列表中已经渲染的项目。 If so, how do I fix that?
如果是这样,我该如何解决?
Thank you!谢谢!
That depends on how you set the state, if you use the provided this.setState
then yes, react will notice and re-render your app.这取决于您如何设置 state,如果您使用提供的
this.setState
那么是的,react 会注意到并重新渲染您的应用程序。 If you instead do state = { /* some new state */ }
then it might not re-render.如果您改为执行
state = { /* some new state */ }
那么它可能不会重新渲染。 I hope this answers your question.我希望这回答了你的问题。
Please next time just check the React docs ( State and Lifecycle )请下次检查 React 文档( State 和 Lifecycle )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.