React中setState几个现象---先知道再理解
发布时间:2020-12-15 06:29:14 所属栏目:百科 来源:网络整理
导读:常规情况 在同一个方法中多次setState是会被合并的,并且对相同属性的设置只保留最后一次的设置; import React from 'react';export class Test extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } componentWill
常规情况在同一个方法中多次setState是会被合并的,并且对相同属性的设置只保留最后一次的设置; import React from 'react'; export class Test extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } componentWillMount() { let me = this; me.setState({ count: me.state.count + 2 }); me.setState({ count: me.state.count + 1 }); } componentDidMount() { let me = this; me.setState({ count: me.state.count + 2 }); me.setState({ count: me.state.count + 1 }); } onClick() { let me = this; me.setState({ count: me.state.count + 1 }); me.setState({ count: me.state.count + 1 }); } render() { console.log(this.state.count); console.log('2222222222222222222222222222222222222222111'); return ( <div> <h1>{this.state.count}</h1> <input type="button" value="点击我" onClick={this.onClick.bind(this)} /><br /> <br /> </div> ) } }
定时器中的setState定时器中的setState,每次都会引起新的render,即使是同一个定时器中的多次setState 代码更改成如下: componentWillMount() { let me = this; setTimeout(() => { me.setState({ count: me.state.count + 1 }); me.setState({ count: me.state.count + 1 }); },0); } componentDidMount() { let me = this; setTimeout(() => { me.setState({ count: me.state.count + 1 }); me.setState({ count: me.state.count + 1 }); },0); } onClickTime() { let me = this; setTimeout(() => { me.setState({ count: me.state.count + 1 }); me.setState({ count: me.state.count + 1 }); },0); } 上述代码,每次 原生事件中的setState在按钮原生事件中定义的 componentDidMount() { this.button.addEventListener('click',this.onClick.bind(this,'原生事件'),false); } onClick(info) { console.log(info); this.setState({ count: ++count }); this.setState({ count: ++count }); } render() { console.log(this.state.count); return <div> <input type="button" ref={input => this.button = input} onClick={this.onClick.bind(this,'React事件')} value="生成计时器" /> <div>Count:{this.state.count}</div> </div> } 点击按钮,先执行原生事件,再执行react事件,但是原生事件会触发两次render,react事件触发一次。 总结上述是我对setState的理解,抛砖引玉,希望帮助大家有方向的去了解react原理机制。刚开始接触,很多同学想深入了解,但可能不知道从何入手,这也是我遇到过的困扰,所以现在分享出来,希望能帮助大家少走弯路,更快的、更有准针对性的去研究学习React。 觉的对自己有帮助的,希望点赞、收藏,鼓励鼓励!!! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |