setState 的同步和异步执行
规则:
setState 处在同步的逻辑中,异步更新状态,异步更新真实 DOM
setState 处在异步的逻辑中,同步更新状态,同步更新真实DOM
什么叫处在异步逻辑中?比如说 setState 函数被包裹在 setTimeout 函数里面执行,这就是其中一种情况
代码实现:
import React, {Component} from 'react';
import BetterScroll from 'better-scroll'
class BetterScrollTest extends Component {
state = {
list: []
}
render() {
return (
<div>
<button onClick={() => this.getData()}>click</button>
<div className="wrapper" style={{height: '200px', backgroundColor: 'yellow', overflow: "hidden"}}>
<ul className="content">
{
this.state.list.map((item, index) => {
return <li key={item}>{item}</li>
})
}
</ul>
</div>
</div>
);
}
getData = () => {
let list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 21, 24];
setTimeout(()=>{
this.setState({
list:list
})
new BetterScroll(".wrapper")
},0)
}
}
export default BetterScrollTest;
|