大前端-万物皆可JS

react最佳实践

2017-05-12  本文已影响87人  Chummy楚寒

react最佳实践(基础篇)

以下仅仅是个人意见或者是react实践中的技巧,只针对代码不针对个人

  • 如果你的变量只是操作逻辑不会 render UI的情况下,请不要放在state中
//解构赋值 
let { state1,state2, state3 } = this.state;
let { prop1, prop2, porp3 } = this.props;
//字符串模板
 `${name}`  
//默认值处理
function toDo(name = "who", age = 12){ //to do }
//展开运算符
let obj = { name ="name", age = 12 };
toDo(...obj)
        <Spin
          spinning={props.switcher.atsFetching !== false}   // ???/
        >
    if('activeIndex' in props){
        //to do
    }
    // 无状态组件接收的参数必须使用 {} 包裹,它传入的是 父组件的props 
    function Button({text='按钮',color='red'}){
        return (
            <button className={btn btn-${color}}>
                <span>${text}</text>
            </button>
        )
    }
    //函数的类型检查是propTypes.func
    //布尔类型的propTypes.bool
    be:避开关键词
    //WillMount会在render之前执行,DidMount则会在render之后执行
    如果在DidMount后又setState则会 re-render
    //在执行reactComponentWillMount的时候进行setState是不会重新re-render的,
    //而是会合并state
    /*
    
    */

!!注意:禁止在shouldComponentUpdate和ComponentWillUpdate中setState,
会导致循环调用直到浏览器耗光了内存

    /*
        如果绑定this不需要传递参数的情况下可以使用::this.handleClick
        而且项目中要使用 stage-0 的提案
    */
    /* 
        在react中使用DOM原生事情,一定要在组件卸载的时候手动移除事件
        否则很有可能会造成内存泄漏
    */
    /*
        不要将合成事件与原生事件混用,否则达不到你想要的效果
    */
    return < input style={{color:'red'}}> //这样每次都会得到新的style对象,造成重新render的性能消耗
    //使用先定义的方式来处理这个问题
    import React from 'react';
    import { is } from 'immutable';

    class App extends Component {
        shouldComponentUpdate(nextProps,nextState){
            const thisProps = this.props || {};
            const thisState = this.state || {};
    
            if(Object.keys(thisProps).length !== Object.keys(nextProps).length
            || Object.keys(thisState).length !== Object.keys(nextState).length){
                return true
            }
    
            for(const key in nextProps){
                if(nextProps.hasOwnProperty(key) && !is( thisProps[key], nextProps[key])){
                    return true
                }
            }
    
            for(const key in nextState){
                if(nextState.hasOwnProperty(key) && !is( thisState[key], nextState[key])){
                    return true
                }
            }
    
            return false
        }
    } 

CSS样式

持续更新....

上一篇 下一篇

猜你喜欢

热点阅读