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

同一个组件里有两次调用setState(),但是只会执行一次render函数,为什么?怎么解决? #49

Open
zyb970821 opened this issue Jun 22, 2021 · 1 comment

Comments

@zyb970821
Copy link

No description provided.

@yuanyinghao1
Copy link

react为了提高整体的渲染性能,会将一次渲染周期中的state进行合并,在这个渲染周期中你对所有setState的所有调用都会被合并起来之后,再一次性的渲染,这样可以避免频繁的调用setState导致频繁的操作dom,提高渲染性能。
解决:
1.this.setState()  【最为常用】这是在事件处理函数中和请求回调函数中触发 UI 更新的主要方法。
一般情况下setState() 总是触发一次重绘,除非在 shouldComponentUpdate() 中实现了条件渲染逻辑。
2.this.forceUpdate() 【较为常用,但是不推荐】
如果 render() 方法从 this.props 或者 this.state 之外的地方读取数据,你需要通过调用 forceUpdate() 告诉 React 什么时候需要再次运行 render()。如果直接改变了 this.state,也需要调用 forceUpdate()。调用 forceUpdate() 将会导致 render() 方法在相应的组件上被调用,并且子级组件也会调用自己的 render(),但是如果标记改变了,那么 React 仅会更新 DOM。通常情况下,应该尽量避免所有使用 forceUpdate() 的情况,在 render() 中仅从 this.props 和 this.state 中读取数据。这会使应用大大简化,并且更加高效。
3.this.setProps()   【不常用】
同一个节点上再次调用 React.render() 来更新根组件是首选的方式,也可以调用 setProps() 来改变组件的属性,触发一次重新渲染。
但是!此方法仅在根组件上面调用。也就是说,仅在直接传给 React.render() 的组件上可用,在它的子级组件上不可用。如果你倾向于在子组件上使用 setProps(),不要利用响应式更新,而是当子组件在 render() 中创建的时候传入新的 prop 到子组件中。

@Dogtiti Dogtiti removed the Cbayel label May 11, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants