简体   繁体   English

更改 state 是否会导致在 ReactJS 中重新渲染

[英]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.

相关问题 更改部分数据后重新渲染状态-reactjs - re-render the state after changing a part of the data - reactjs Reactjs - SetTimeout 与 state 更改重新渲染 - Reactjs - SetTimeout with state change re-render ReactJs在状态改变时重新渲染 - ReactJs re-render on state change React 状态不会重新渲染 - React state does not re-render 即使状态已更改,成功的调度也不会导致重新渲染 - Successful dispatch does not cause re-render even though state has been changed 为什么每个状态钩子更新都会导致异步代码中的单独重新渲染? - Why does each state hook update cause a separate re-render in asynchronous code? 为什么 getDerivedStateFromProps 不允许使用 state 更新重新渲染? componentWillReceiveProps 不是问题 - ReactJS - Why getDerivedStateFromProps does not allow to re-render with the state update? Not a problem for componentWillReceiveProps - ReactJS ReactJS:类型数组的状态在重新渲染期间被分解为元素 - ReactJS: State of type array is deconstructing into element during re-render 如何在状态更改时重新渲染子组件(父级)reactjs - how to re-render child component on state change(Parent) reactjs 为什么即使 StaticComponent 没有更改 state 也会重新渲染? - Why does StaticComponent re-render even though it has no changing state?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM