[React笔记]一些要注意的点

Markdown
在React中要注意在componentWillUpadate 中不能用 this.setState() 方法。

componentWillUpadate

问题的出现

在学习的时候,有一个例子的要求是,

使用componentWillUpdate()方法修改示例代码,使时钟在秒为0时显示为红色字体!

我一开始在componentWillUpadate()中 写的是

1
2
3
4
5
6
7
...
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.

代码如下:

See the Pen LWbYKY by ziazan (@ziazan) on CodePen.

官网上上说的是在componentWillUpadate 中不能用 this.setState() 方法。

设置组件style

设置组件中的style属性时,要双大括号:

1
2
3
<div className="ez-digi-clock" style={{color:this.state.color}}>
{this.state.time}
</div>

这是因为 React 组件样式是一个对象,所以第一重大括号表示这是 JavaScript 语法,第二重大括号表示样式对象

------ 本文结束 ------
谢谢打赏~
Fork me on GitHub