React中setState同步更新策略
setState 同步更新我们在上文中提及,为了提高性能React将setState设置为批次更新,即是异步操作函数,并不能以顺序控制流的方式设置某些事件,我们也不能依赖于 componentDidMount() { fetch('https://example.com') .then((res) => res.json()) .then( (something) => { this.setState({ something }); StatusBar.setNetworkActivityIndicatorVisible(false); } ); } 因为 this.setState({showForm : !this.state.showForm}); 我们预期的效果是每次事件触发后改变表单的可见性,但是在大型应用程序中如果事件的触发速度快于 完成回调
this.setState({ load: !this.state.load,count: this.state.count + 1 },() => { console.log(this.state.count); console.log('加载完成') }); 这里的回调函数用法相信大家很熟悉,就是JavaScript异步编程相关知识,我们可以引入Promise来封装setState: setStateAsync(state) { return new Promise((resolve) => { this.setState(state,resolve) }); }
async componentDidMount() { StatusBar.setNetworkActivityIndicatorVisible(true) const res = await fetch('https://api.ipify.org?format=json') const {ip} = await res.json() await this.setStateAsync({ipAddress: ip}) StatusBar.setNetworkActivityIndicatorVisible(false) } 这里我们就可以保证在 class AwesomeProject extends Component { state = {} setStateAsync(state) { ... } async componentDidMount() { ... } render() { return ( <View style={styles.container}> <Text style={styles.welcome}> My IP is {this.state.ipAddress || 'Unknown'} </Text> </View> ); } } 该组件的执行效果如下所示: 传入状态计算函数除了使用回调函数的方式监听状态更新结果之外,React还允许我们传入某个状态计算函数而不是对象来作为第一个参数。状态计算函数能够为我们提供可信赖的组件的State与Props值,即会自动地将我们的状态更新操作添加到队列中并等待前面的更新完毕后传入最新的状态值: this.setState(function(prevState,props){ return {showForm: !prevState.showForm} }); 这里我们以简单的计数器为例,我们希望用户点击按钮之后将计数值连加两次,基本的组件为: class Counter extends React.Component{ constructor(props){ super(props); this.state = {count : 0} this.incrementCount = this.incrementCount.bind(this) } incrementCount(){ ... } render(){ return <div> <button onClick={this.incrementCount}>Increment</button> <div>{this.state.count}</div> </div> } } 直观的写法我们可以连续调用两次 incrementCount(){ this.setState({count : this.state.count + 1}) this.setState({count : this.state.count + 1}) } 上述代码的效果是每次点击之后计数值只会加1,实际上第二个 incrementCount(){ this.setState((prevState,props) => ({ count: prevState.count + 1 })); this.setState((prevState,props) => ({ count: prevState.count + 1 })); } 这里的第二个 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |