react组件开发规范总结

时间:2024-01-19 08:47:50

开发react也有一段时间了,一开始的随手写,生命周期乱用,无状态组件的不熟悉。现在逐渐规范一下,从网上各个地方copy过来,整理出一份文档。可能不全,后续还得多提炼总结和完善。

一、组件内方法书写,先写生命周期函数(按执行顺序写),再写自定义函数。

import React,{ Component } from 'react';

class Demo extends Component {
constructor(props,context) {
super(props,context)
this.state = {
//定义state
}
}
componentWillMount () {
}
componentDidMount () {
}
componentWillReceiveProps (nextProps) {
}
shouldComponentUpdate (nextProps,nextState) {
}
componentWillUpdate (nextProps,nextState) {
}
componentDidUpdate (prevProps,prevState) {
}
componentWillUnmount () {
} yourMethoed1(){
} yourMethoed2(){
}
render () {
return (
<div></div>
)
} }
export default Demo;

二、事件this绑定放到constrcutor构造函数中

import React,{ Component } from 'react';

class Demo extends Component {
constructor(props,context) {
super(props,context)
this.state = {
//定义state
}
this.handlerMethod = this.handlerMethod.bind(this)
} render () {
return (
<div></div>
)
}
}
export default Demo; // 不推荐写法:
<div onClick={this.handlerMethod.bind(this)}>do some actions</div>

三、组件一定要有prop传入类型校验,即要写PropTypes

注意:prop-types是第三方的npm包。react16版本后,自己不再维护PropTypes。因此要引用第三方的

import React,{Component} from 'react';
import PropTypes from 'prop-types';
class App extends Component{
render(){
return <div>{this.props.name}</div>
}
}
App. propTypes = {
name: PropTypes.string
}

四、异步获取数据请求放到componentDidMount中

五、尽量不要在钩子函数外使用setState方法,以及setTimeout中,不要在componentWillUpdate/componentDidUpdate/render中执行setState, 可能异致死循环。

六、访问真实dom方式:refs

<AudioCompoent  ref={(ref) => { this.myRef = ref; }}/>

// 不推荐
<AudioCompoent ref="myRef"/>

七、render方法内尽量少申明变量

八、数据遍历组件的时候要有key属性,但是不要用数组下标作为key

render() {
return (
<ul>
{this.state.sort.map((item, index) => {
return <li key={item.name}>
{item.name} <input type=“text”/>// 假定name是唯一的
</li> })}
</ul> );
}

九、简单展示类型,不涉及到state的组件,用function 函数声明式的无状态组件。

import React, {PropTypes} from 'react'
import {connect} from 'react-redux' const dataType = {
onExpand: PropTypes.func.isRequired,
isOpen: PropTypes.bool
} const List = ({ onExpand, expanded = false, childred }) =>
<form style={ expanded ? { height: 'auto' } : { height: } }>
{children}
<button onClick={onExpand}>Expand</button>
</form>; List.propTypes = dataType export default connect(List)