在React中要注意在componentWillUpadate 中不能用 this.setState() 方法。
componentWillUpadate
问题的出现
在学习的时候,有一个例子的要求是,
使用componentWillUpdate()方法修改示例代码,使时钟在秒为0时显示为红色字体!
我一开始在componentWillUpadate()中 写的是
……
componentWillUpadate:function(){
if(this.state.time.split(':')[2] === '00'){
this.state. = 'red';
}
}
……
程序报bug了。
我去找原因:
You cannot use this.setState() in componentWillUpadate . If you need to update state in response to a prop change, use componentWillReceiveProps instead.
代码如下:
height="265" scrolling="no" title="LWbYKY" src="//codepen.io/ziazan/embed/LWbYKY/?height=265&theme-id=0&default-tab=js,result&embed-version=2" allowfullscreen="true">See the Pen <a href="http://codepen.io/ziazan/pen/LWbYKY/">LWbYKY</a> by ziazan (<a href="http://codepen.io/ziazan">@ziazan</a>) on <a href="http://codepen.io">CodePen</a>. 官网上上说的是在componentWillUpadate 中不能用 this.setState() 方法。
设置组件style
设置组件中的style属性时,要双大括号:
<div className="ez-digi-clock" style={{color:this.state.color}}>
{this.state.time}
</div>
这是因为 React 组件样式是一个对象,所以第一重大括号表示这是 JavaScript 语法,第二重大括号表示样式对象