React操作失误笔记
前言
一些我在学习React里的操作失误
问题
1.未绑定就引用有this的函数
TypeError: Cannot read property ‘timer’ of undefined
以下是使用onMouseOut引用out函数
<div className="big" onMouseOut={this.out} onMouseOver={this.over}>
问题:未使用bind绑定事件,修改方法(1)如下
<div className="big" onMouseOut={this.out.bind(this)} onMouseOver={this.over.bind(this)}>
修改方法(2)在constructor内绑定
this.out = this.out.bind(this);
this.over = this.over.bind(this);
2.引用方法错误
Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
在render()内创建的元素,如果需要修改属性的值,那么里面添加的应该是方法(函数)而不是直接修改,修改方法(创建函数然后引用函数)如下
<div className="spot" onClick={() => {this.setState({No: 3})}} > 4 </div>
<div className="spot" onClick={() => {this.setState({No: 2})}} > 3 </div>
<div className="spot" onClick={() => {this.setState({No: 1})}} > 2 </div>
<div className="spot" onClick={() => {this.setState({No: 0})}} > 1 </div>
3.setState的异步与回调函数解决
在处理按钮点击事件的处理上往往会遇到这么个问题
<div className="spot" onClick={() => {this.setState({No: 3, left: this.state.No*width})}} > 4 </div>
<div className="spot" onClick={() => {this.setState({No: 2, left: this.state.No*width})}} > 3 </div>
<div className="spot" onClick={() => {this.setState({No: 1, left: this.state.No*width})}} > 2 </div>
<div className="spot" onClick={() => {this.setState({No: 0, left: this.state.No*width})}} > 1 </div>
这里运用setState更新No的值然后再引用,结果就是并没有更新。
因为setState是异步的,当渲染结束后才会再次更新,因此同时传参只能传上一步的值。
解决方法:这里可以运用回调函数,根据另外设的新函数,然后将No的参数传入,然后使用回调函数引用,此时在新函数内No的值就可以使用传入的数字
<div className="spot" onClick={(event) => {
this.spot(3)
}} > 4 </div>
<div className="spot" onClick={(event) => {
this.spot(2)
}} > 3 </div>
<div className="spot" onClick={(event) => {
this.spot(1)
}} > 2 </div>
<div className="spot" onClick={(event) => {
this.spot(0)
}} > 1 </div>
以下是spot函数内容:
spot(No){
this.setState({
No: No,
left: No* width
})
}
总结
持续更新中,多出错多总结