在可復(fù)用組件而不是可復(fù)用函數(shù)時談過react的組件化而钞。當(dāng)時正在忙于微信電影票的重構(gòu)冰更,寫了大量拼湊的模板函數(shù)裕膀。
在文章寫之后就對微信電影票選座頁代碼中拼湊的模板函數(shù)進行了復(fù)寫辑鲤。以組件的形式展示。但因為一些歷史原因喷屋,中心座位圖的部分代碼沒辦法改動琳拨。這次終于下定決心把中心選座區(qū)的代碼重新了一遍,對組件化的理解又加深了一步屯曹。加上通過組件生命周期的靈活設(shè)置从绘,避免了重復(fù)渲染寄疏,提高了性能。
組件化
先來看一下使用拼湊的模板函數(shù)來寫出的可復(fù)用函數(shù)
export default class Home extends Page {
constructor(...args) {
super(...args)
this.state = {
movieName: '奇異博士',
movieTime: '12:40'
}
}
renderMovie(movieName) {
//...
return (
<div>{movieName}</div>
)
}
renderMovieTime(movieTime) {
return (
<div>{movieTime}</div>
}
changeMovieName() {
this.setState = {
movieName: '蠟筆小新'
}
changeMovieTime() {
this.setState = {
movieTime: '12:50'
}
}
render() {
let { movieName, movieTime } = this.state
return(
<div onClick={this.changeMovieName.bind(this)}>...</div>
<div>{renderMovie(this, movieName)}</div>
<div>{renderMovieTime(this, movieTime)}</div>
<div onClick={this.changeMovieTime.bind(this)}>...</div>
)
}
}
好像也沒什么問題僵井,當(dāng)時只是覺得這種寫法不太符合組件化的思想,只是把以前JQuery的想法直接拿來寫react
但在經(jīng)歷選座頁組件化復(fù)寫之后驳棱,總結(jié)出了這樣寫實際的弊端:
- 拼湊的模板函數(shù)沒有對傳入的參數(shù)進行校驗批什,后續(xù)修改與維護不方便。
- 拼湊的模板函數(shù)只能寫到該組件內(nèi)部社搅,很難被其他頁面引用驻债。
- 只要props或者state改變,拼湊的模板函數(shù)就會重新渲染形葬,多余的渲染必然造成性能的下降
知道了拼湊的模板函數(shù)弊端之后合呐,現(xiàn)在我們把上面的代碼轉(zhuǎn)化成組件的形式
//home.js
import Movie from './Movie'
import MovieTime from './MovieTime'
export default class Home extends React.Component {
constructor(...args) {
super(...args)
this.state = {
movieName: '奇異博士',
movieTime: '12:40'
}
}
changeMovieName() {
this.setState = {
movieName: '蠟筆小新'
}
changeMovieTime() {
this.setState = {
movieTime: '12:50'
}
}
render() {
let { movieName, movieTime } = this.state
return(
<div onClick={this.changeMovieName.bind(this)}>...</div>
<Movie movieName={movieName} />
<MovieTime movieTime={movieTime} />
<div onClick={this.changeMovieTime.bind(this)}>...</div>
)
}
}
//Movie.js
class Movie extends React.Component {
shouldComponentUpdate(nextProps) {
const { movieName } = this.props
return movieName === nextProps.movieName
}
render() {
const { movieName } = this.props
return(
<div>{movieName}</div>
}
}
export default props => {
const { movieName} = props
return (
<Movie movieName={movieName} />
)
}
Movie.propTypes = {
movieName: React.PropTypes.string.isRequired,
}
//MovieTime.js
class MovieTime extends React.Component {
shouldComponentUpdate(nextProps) {
const { movieTime } = this.props
return movieTime === nextProps.movieTime
}
render() {
const { movieTime } = this.props
return(
<div>{movieTime}</div>
}
}
export default props => {
const { movieTime} = props
return (
<MovieTime movieTime={movieTime} />
)
}
MovieTime.propTypes = {
movieTime: React.PropTypes.string.isRequired,
}
通過propType進行組件參數(shù)校驗。通過shouldComponentUpdate控制渲染性能笙以,避免重復(fù)渲染淌实。后續(xù)Movie和MovieTime組件也能夠被其他頁面很方便的調(diào)用。
這就是react組件的正確使用方法猖腕。關(guān)于通過propType來規(guī)范組件的props的類型拆祈,后續(xù)再專門寫篇文章講吧~