setState异步更新状态,更新真实dom
这时候可以使用 react-dom 提供的 flushSync,使得同步更新 dom:
import React, { Component } from 'react'
import { flushSync } from 'react-dom';
export default class App extends Component {
state = {
count: 1
}
render() {
return (
<div>
{this.state.count}
<button onClick={() => this.handleAdd1()}>+</button>
</div>
)
}
handleAdd1 = () => {
flushSync(()=>{
this.setState({
count: this.state.count + 1
})
this.setState({
count: this.state.count + 1
})
})
console.log(this.state.count)//即可同步更新dom
}
}
/*
setState异步更新状态,更新真实dom
*/
this.setState({value: 42}, () => { // 在此处执行需要同步更新的操作 });
setState接受第二个参数,第二个参数是回调函数,状态和dom更新完后就会被触发
better-scroll:
方案一
import React, { Component } from 'react'
import BetterScroll from 'better-scroll'
export default class App extends Component {
state = {
list:[]
}
render() {
return (
<div>
<button onClick={this.handleClick.bind(this)}>click</button>
<div className="wrapper" style={{height:'200px',overflow:'hidden'}}>
<ul className="content">
{
this.state.list.map(function(item,index){
return <li key={index}>{item}</li>
})
}
</ul>
</div>
</div>
)
}
handleClick(){
var list=[1,2,3,4,5,6,7,8,9,10,11,12,13,14]
this.setState({list:list},()=>{
new BetterScroll(".wrapper")
})
}
}
方案二
import { flushSync } from 'react-dom'
handleClick(){
var list=[1,2,3,4,5,6,7,8,9,10,11,12,13,14]
flushSync(()=>{
this.setState({list:list})
})
new BetterScroll(".wrapper")
}
相关作者
- 获取点赞0
- 文章阅读量264
评论()