本文主要说6条给React开发者的专业建议,让你写出更好的React代码

1. 使用方法组件

在你不需要使用组建的内部状态和生命周期方法
你可以使用

1
2
3
function welcome(props){
return <h1>Hello,{props.name}</h1>;
}

来代替

1
2
3
4
5
class Welcome extends Component{
render(){
return <h1>Hello,{this.props.name}</h1>
}
}

使用这种方法的好处:
  • 更少的代码,
  • 更容易理解,
  • 不用处理状态机,
  • 测试简单,
  • 不需要绑定this,
  • 更容易提取较小的组件

2.尽可能的让你的组件小巧

使用这种方法的好处:

  • 便于阅读
  • 便于测试
  • 方便维护
  • 方便复用

    例如:下面我们把个人中心资料模块进行细分

个人用户信息部分被拆分

1
2
3
4
5
6
7
8
9
10
11
12
class Comment extends Compont{
render()
<div className="Comment">
<UserInfo user={this.props.user}/>
<div className='Comment-text'>
{this.props.text}
</div>
<div className="comment-text">
{formatDate(this.props.date)}
</div>
</div>
}

在用户信息部分中,头像部分也被拆分成更小的组件

1
2
3
4
5
6
7
8
9
10
function UserInfo(props){
renturn (
<div className="UserInfo">
<Avatar user={props.name}/>
<div classNmae='UserInfo-name'>
{props.user.name}
</div>
</div>
);
}

个人头像部分

1
2
3
4
5
6
7
8
function Avatar(props){
return(
<img className='Avatar'
src={props.user.avatarUrl}
alt={props.user.name}
</img>
);
}

3.了解并知道怎样处理’this’

1. 在render中绑定

这种方式虽然简单明了但是有性能问题,因为点击后会调用一个新的函数,每次这个组件都要重新渲染

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class HelloWorld extend component{
contructor(props){
super(props);
this.state={message:'Hi'};
}
logMessage(){
console.log(this.state.message);
}
render(){
return {
<input type='button' value='Log' onClick={this.logMessage.bind(this)}/>
}
}
}

2. 在render中使用箭头函数

这种方式和方法1同样会有相同的性能问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class HelloWorld extend component{
contructor(props){
super(props);
this.state={message:'Hi'};
}
logMessage(){
console.log(this.state.message);
}
render(){
return {
<input type='button' value='Log' onClick={()=>this.logMessage}/>
}
}
}

3. 在构造方法中绑定

这种方式需要记得使用super(props)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class HelloWorld extend component{
contructor(props){
super(props);
this.state={message:'Hi'};
this.logMessage= this.logMessage.bind(this)
}
logMessage(){
console.log(this.state.message);
}
render(){
return {
<input type='button' value='Log' onClick={this.logMessage}/>
}
}
}

4. 在属性中使用箭头函数

有方法1和2的性能问题

1
2
3
4
5
6
7
8
9
10
11
12
13
class HelloWorld extend component{

this.state={message:'Hi'};

logMessage=()=>{
console.log(this.state.message);
}
render(){
return {
<input type='button' value='Log' onClick={this.logMessage}/>
}
}
}

4.在更新状态时使用方法而不是对象

user:

1
2
3
this.setState((prevState.props)=>{
renturn {correctData:!prevState.correctData}
});

not

1
this.setState({correctData:!this.state.correctData});

5.开发lib时使用’prop-types’

1
2
3
4
5
6
7
8
9
10
11
import PropTypes from 'pros-types';

class Welcome extends Component{
render(){
return <h1>Hello,{this.props.name}</h1>

}
}
Welcome.propTypes={
name:ProsTypes.string.isRequired
}

6.使用必要的React 开发工具来帮助我们