react-native性能优化的考虑

性能优化的学习

React Component的性能考虑

1 createClass 和 extends React.component

es5的写法 。。。es6的写法。没有绝对的性能好坏之分,只不过createClass支持定义PureRenderMixin,这种写法官方已经不再推荐,而是建议使用PureComponent。

2 Component 和 PureComponent

shouldComponentUpdate(nextProps,nextState){ if(this.state.disenter !== nextState.disenter){ return true } return false; }
shouldComponentUpdate通过判断 state.disenter是否发生变化来决定需不需要重新渲染组件,当然在组件中加上这种简单判断,显得有些多余和样板化,于是React就提供了PureComponent来自动帮我们做这件事。这样就不需要手动来写shouldComponentUpdate了。

class CounterButton extends React.PureComponent {
constructor(props) {
super(props); this.state = {count: 1}; }

render() {
return (
<button color={this.props.color} onClick={() => this.setState(state => ({count: state.count + 1}))}> Count: {this.state.count} </button>
); } }
大多数请客下,我们使用PureComponent能够简化代码,并且提高性能,但是PureComponent的自动为我们添加的shouldComponentUpdate,只是对props和state进行浅比较。

当props或者state本身是嵌套对象或者数组等时,浅比较并不能得到预期的结果。这会导致实际 的props和state发生了变化,但组件却没有更新的问题。

例如:
class WordAdder extends React.Component {
constructor(props) {
super(props);
this.state = {
words: ['marklar']
}; this.handleClick = this.handleClick.bind(this); }

handleClick() {
// 这个地方导致了bug
const words = this.state.words;
words.push('marklar');
this.setState({words: words}); }
这种情况下,PureComponent只会对this.props.words进行一次浅比较,虽然数组里面新增了元素,但是this.props.words与nextProps.words指向的仍是同一个数组,因此this.props.words !== nextProps.words 返回的便是flase,从而导致ListOfWords组件没有重新渲染,笔者之前就因为对此不太了解,而随意使用PureComponent,导致state发生变化,而视图就是不更新,调了好久找不到原因。
最简单避免上述情况的方式,就是避免使用可变对象作为props和state,取而代之的是每次返回一个全新的对象,如下通过concat来返回新的数组:

handleClick(){
 this.setState(prevState=>({
    disenter:prevState.disenter.concat(['nothing'])
}))}

可以考虑使用immutable.js来创建不可变对象,通过它来简化对象比较,提高性能,这里还要提到的一点是虽然这里使用Pure这个词,但是PureComponent并不是纯的,因为对于纯的函数或组件应该是没有内部状态,对于stateless component更符合纯的定义。

3 Component 和 Stateless Functional component

createClass Component PureComponent都是通过创建包含状态和用户交互的复杂组件,当组件本身只是用来展示,所有数据都是通过props传入的时候,我们可以使用Stateless Functional component来快速创建组件,

const DAY =({
    min,
    second,     
})=>{
    return(
        <View>
            <Text>{min}:{second}</Text>
        </View>
    )
}

这种组件,没有自身的状态,相同的props输入,必然会获得完全相同的组件展示,因为不需要关心组件的一些生命周期函数和渲染的钩子。让代码显得更加简洁。

总结:在平时的开发的时候,多考虑React的生命周期

eg:

class LifeCycle extends React.Component {
constructor(props) { super(props); alert("Initial render"); alert("constructor"); this.state = {str: "hello"}; }

componentWillMount() {
    alert("componentWillMount");
}

componentDidMount() {
    alert("componentDidMount");
}

componentWillReceiveProps(nextProps) {
    alert("componentWillReceiveProps");
}

shouldComponentUpdate() {
    alert("shouldComponentUpdate");
    return true;        // 记得要返回true
}

componentWillUpdate() {
    alert("componentWillUpdate");
}

componentDidUpdate() {
    alert("componentDidUpdate");
}

componentWillUnmount() {
    alert("componentWillUnmount");
}

setTheState() {
    let s = "hello";
    if (this.state.str === s) {
        s = "HELLO";
    }
    this.setState({
        str: s
    });
}

forceItUpdate() {
    this.forceUpdate();
}

render() {
    alert("render");
    return(
        <div>
            <span>{"Props:"}<h2>{parseInt(this.props.num)}</h2></span>
            <br />
            <span>{"State:"}<h2>{this.state.str}</h2></span>
        </div>
    );
}

}

class Container extends React.Component { constructor(props) { super(props); this.state = { num: Math.random() * 100 };
}

propsChange() {
    this.setState({
        num: Math.random() * 100
    });
}

setLifeCycleState() {
    this.refs.rLifeCycle.setTheState();
}

forceLifeCycleUpdate() {
    this.refs.rLifeCycle.forceItUpdate();
}

unmountLifeCycle() {
    // 这里卸载父组件也会导致卸载子组件
    React.unmountComponentAtNode(document.getElementById("container"));
}

parentForceUpdate() {
    this.forceUpdate();
}

render() {
    return (
        <div>
            <a href="javascript:;" className="weui_btn weui_btn_primary" onClick={this.propsChange.bind(this)}>propsChange</a>
            <a href="javascript:;" className="weui_btn weui_btn_primary" onClick={this.setLifeCycleState.bind(this)}>setState</a>
            <a href="javascript:;" className="weui_btn weui_btn_primary" onClick={this.forceLifeCycleUpdate.bind(this)}>forceUpdate</a>
            <a href="javascript:;" className="weui_btn weui_btn_primary" onClick={this.unmountLifeCycle.bind(this)}>unmount</a>
            <a href="javascript:;" className="weui_btn weui_btn_primary" onClick={this.parentForceUpdate.bind(this)}>parentForceUpdateWithoutChange</a>
            <LifeCycle ref="rLifeCycle" num={this.state.num}></LifeCycle>
        </div>
    );
}

}

ReactDom.render( <Container></Container>, document.getElementById('container') );

运行该例子,可以发现生活周期的运行顺序为:

initial render---
constructor----
componentWillMount----
render---
componentDidMount----
render

初始状态下,加载页面所走的流程。

(propsChange)
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
render
componentDidUpdate

属性的改变。所走的生命周期

(setState)
shouldComponentUpdate
componentWillUpdate
render
componentDidUpdate

这是我们在平时开发中,正常会使用state来更改渲染

(forceUpdate)
componentWillUpdate
render
componentDidUpdate

当我们开发中出现不渲染的情况,可以使用forceUpdate。因为在shouldComponentUpdate正常来说,是返回为true,当前state,和nextState,或者当前props和nextProps的时候,会因为state,props嵌套在数组或对象中,而指向同一个数组或对象,这时候,可以使用forceUpdate, 即:-->组件不走‘shouldComponentUpdate’

(unmount)
componentWillUnmount

卸载。通常有定时器或者监听的时候需要在此方法内卸载。

(parentForceUpdateWithoutChange)
componentWillReceiveProps
shouldComponentUpdate
componentWillUpdate
render
componentDidUpdate


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,026评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,655评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,726评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,204评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,558评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,731评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,944评论 2 314
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,698评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,438评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,633评论 2 247
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,125评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,444评论 3 255
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,137评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,103评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,888评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,772评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,669评论 2 271

推荐阅读更多精彩内容