组件的设计

设计流程

  1. 画一个简单的原型图,将所有功能可视化的表现出来
  2. 使用react编写静态组件
    • 利用map去循环列表的时候,记得要加上key值
  3. 组合静态组件,尽可能的将组件设计成无状态组件
    • mock出一些数据,供组件使用
  4. 在组件中添加state
    • state的设计原则是尽量最简化数据,遵循DRY(Don't repeat Yourself)的原则
  5. 组件交互设计
    • 总计需要进行的操作:CURD、界面操作
    • 将这些操作添加到静态组件上

一个良好的react应用,应该包括尽可能多的无状态组件加上一个包含state的总组件。无状态组件用来单纯渲染UI,只用关注传入的props即可。包含state的总组件用来处理事件、逻辑和管理state。

避免使用反模式

反模式:存在性能低效又有待优化的设计模式

反模式一:基于props得到初始state

getInitialState:function(){
    return {
        name:this.props.name
    }
}

解决方法

  • jsx中计算后渲染或者直接渲染
  • 如果state只是用prop初始化数据,而不是需要基于prop去更改,那么这种做法是合理的。那么我们在属性上加上initial或者default的前缀,表示只用于初始化
  • 考虑组件的设计是否合理

反模式二:使用refs获取子组件

直接使用refs去获取子组件的引用及调用方法是没错的,但是调用方法的同时去触发状态变更的方法通常是有问题的。比如以下:

//    parent component
const ParentComponent  = React.createClass({
    render:function(){
        return {
            <div>
            <button onClick={this.updateNotify}>
            <subComponent ref="myComponent"/>
            </div>
        }
    },
    updateNotify:function(content){
       this.refs.myComponnet.notify('子组件的通知事件')
    }
})

//    sub component
const SubComponent  = React.createClass({
    render:function(){},
    notify:function(content){
        this.setState({
            content:content
        })
    }
})

解决方法:尽可能的使用prop

//    parent component
const ParentComponent  = React.createClass({
    render:function(){
        return {
            <div>
            <button onClick={this.updateNotify}>
            <subComponent content={this.state.notificaiton}/>
            </div>
        }
    },
    getInitialState:funciton(){
        return {
            notificaiton:null
        }
    },
    updateNotify:function(){
        this.setState({
            notificaiton:"传递给子组件数据"
        })
    }
})

//    sub component
const SubComponent  = React.createClass({
    render:function(){
        const content = this.props.content;
    },
})

反模式三:数据冗余

即一份数据在state和prop中保存多份

解决方法

  • 保持良好的组件设计和数据结构设计

参考

React 哲学 – React