React 之容器组件和展示组件相分离解密
那么为什么需要容器组件和展示组件相分离呢? 这里有个基本原则:容器组件仅仅做数据提取,然后渲染对应的子组件,记住这个点,Trust me! 看下面这个展示列表的例子,不区分容器和展示组件的情况 // CommentList.js class CommentList extends React.Component { constructor() { super(); this.state = { comments: [] } } componentDidMount() { $.ajax({ url: "/my-comments.json",dataType: 'json',success: function(comments) { this.setState({comments: comments}); }.bind(this) }); } render() { return <ul> {this.state.comments.map(renderComment)} </ul>; } renderComment({body,author}) { return <li>{body}—{author}</li>; } }
那么来看下分离的情况: // CommentListContainer.js class CommentListContainer extends React.Component { constructor() { super(); this.state = { comments: [] } } componentDidMount() { $.ajax({ url: "/my-comments.json",success: function(comments) { this.setState({comments: comments}); }.bind(this) }); } render() { return <CommentList comments={this.state.comments} />; } } // CommentList.js class CommentList extends React.Component { constructor(props) { super(props); } render() { return <ul> {this.props.comments.map(renderComment)} </ul>; } renderComment({body,author}) { return <li>{body}—{author}</li>; } } 这样就做到了数据提取和渲染分离,CommentList可以复用,CommentList可以设置PropTypes判断数据的可用性 来看下容器组件和展示组件的区别:
优势:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |