现在使用react写代码时,有两种写法
一种是
class App extends Component{
constructor(props){
super(props)
this.state={status:true}
}
doSomething:()=>{
this.setState({status:false})
}
render(){
return (<div><button onClick={this.doSomething}>点击</button></div>)
}
}
另一种是
class App extends Component{
constructor(props){
super(props)
this.state={status:true}
}
render(){
return (<div><button onClick={()=>this.setState({status:false})}>点击</button></div>)
}
}
想知道这两种到底有什么区别,哪种方式更好?
楼上说的全都不准确
这两种写法是有重大区别的。
在第二种写法里,每次
<button>
被重渲染时,传入的onClick
都是一个新创建的函数。你的例子用的是
<button>
还好,用起来效果不会有区别,但如果是你自定义的组件就不一样了。如果你在自定义组件里实现
componentWillReceiveProps
钩子如下:用第二种写法传递的话会发现结果永远是
false
,而用第一种则是true
。这带来的影响到你做性能优化的时候就会体现出来了,会增加不必要的重渲染。
虽然影响也许不大,虽然第二种写法并不是必要改成第一种,还是希望你能知道这两种写法并不像楼上所说的没有区别。