您的位置:首页 > Web前端 > React

React 的几个需要注意的地方

2017-02-01 22:37 405 查看
1.写组件时,最好将一个大的组件分解成多个小的组件。

  通过React写组件时,应当尽可能地将组件分为更小的更多的组件,然后再复合组件。

  比如下面的评论组件就是一个组件,一个庞大的组件,这时我们还没有将之分解,更没有复合: 

function Comment(props) {
return (
<div className="Comment">
<div className="UserInfo">
<img className="Avatar"
src={props.author.avatarUrl}
alt={props.author.name}
/>
<div className="UserInfo-name">
{props.author.name}
</div>
</div>
<div className="Comment-text">
{props.text}
</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
);
}


  这个组件要接受一个author(对象)、一个text(字符串)和一个data(data对象)作为props。

  因为这样的复杂嵌套关系导致如果我们需要修改这个组件变得非常棘手,并且在这种情况下,我们很难能够重用其中的小的组件,因此,这时候我们就需要将这个大的组件分解为几个小的组件,这样对于大的app,我们的工作就会变得越来越容易。

  我们将之分解如下:

  

function formatDate(date) {
return date.toLocaleDateString();
}

function Avatar(props) {
return (
<img className="Avatar"
src={props.user.avatarUrl}
alt={props.user.name} />
);
}

function UserInfo(props) {
return (
<div className="UserInfo">
<Avatar user={props.user} />
<div className="UserInfo-name">
{props.user.name}
</div>
</div>
);
}

function Comment(props) {
return (
<div className="Comment">
<UserInfo user={props.author} />
<div className="Comment-text">
{props.text}
</div>
<div className="Comment-date">
{formatDate(props.date)}
</div>
</div>
);
}

const comment = {
date: new Date(),
text: 'I hope you enjoy learning React!',
author: {
name: 'Hello Kitty',
avatarUrl: 'http://placekitten.com/g/64/64'
}
};
ReactDOM.render(
<Comment
date={comment.date}
text={comment.text}
author={comment.author} />,
document.getElementById('root')
);


  这样,我们就把一个大的组件分解成了几个小的组件并且组合起来,这样更有利于代码的重用以及后期的维护。

2. 组件的props是只读的。

  当我们使用函数的方法定义一个组件的时候,我们是不能修改它的 props的。

  看下面这个函数:

function sum(a, b) {
return a + b;
}


  这种类型的函数我们称为“pure”, 因为它没有尝试着去改变它的Input,并且对于同样的输入总是返回同样的结果。

  对比之下,下面的这种函数就是"impure"的,因为它改变了自己的输入:

function withdraw(account, amount) {
account.total -= amount;
}


  React是非常灵活的,但是它有自己严格的规则;
  所有的React组件关于它们的props都必须表现得像 “pure” 函数。

3.修改组件的state

  虽然说props是只读的,但是state却是可以修改的,可也不能随意修改,如下就是错的方式: 

// Wrong
this.state.comment = 'Hello';


  相反,我们需要使用setState(),如下所示:

// Correct
this.setState({comment: 'Hello'});


  并且如果我们使用es6的class创建组件,设置state初始值的唯一方式就是在constructor中设置(具体可以在mdn中学习es6)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: