摘要:檢查空值不要去檢查是否存在某個(gè)值,快使用。當(dāng)你的值是對(duì)象或者數(shù)組時(shí),使用聲明嵌套數(shù)據(jù)的預(yù)期類型。命名事件可以使用自定義事件替代預(yù)設(shè)的事件名。
原文:react-patterns
代碼結(jié)構(gòu)
class definition
constructor
event handlers
"component" lifecycle
getters
render
defaultProps
proptypes
class Person extends React.Component { constructor (props) { super(props); this.state = { smiling: false }; this.handleClick = () => { this.setState({smiling: !this.state.smiling}); }; } componentWillMount () { // add event listeners (Flux Store, WebSocket, document, etc.) }, componentDidMount () { // React.getDOMNode() }, componentWillUnmount () { // remove event listeners (Flux Store, WebSocket, document, etc.) }, get smilingMessage () { return (this.state.smiling) ? "is smiling" : ""; } render () { return (格式化屬性{this.props.name} {this.smilingMessage}); }, } Person.defaultProps = { name: "Guest" }; Person.propTypes = { name: React.PropTypes.string };
當(dāng)有2個(gè)以上屬性時(shí),就換行顯示
// bad// good
// bad依賴屬性// good
使用getters方法代替定義依賴屬性
// bad firstAndLastName () { return `${this.props.firstName} ${this.props.lastname}`; } // good get fullName () { return `${this.props.firstName} ${this.props.lastname}`; }依賴狀態(tài)
使用getters方法代替定義依賴狀態(tài),注意為了提高可讀性需要在命名時(shí)加上一個(gè)動(dòng)詞前綴。
// bad happyAndKnowsIt () { return this.state.happy && this.state.knowsIt; }
// good get isHappyAndKnowsIt () { return this.state.happy && this.state.knowsIt; }
這些方法必須返回boolean類型
用三元運(yùn)算代替Sub-render方法保證渲染邏輯都寫在render方法里
// bad renderSmilingStatement () { return {(this.state.isSmiling) ? " is smiling." : ""}; }, render () { return{this.props.name}{this.renderSmilingStatement()}; }
// good render () { return (視圖組件{this.props.name} {(this.state.smiling) ? is smiling : null }); }
用定義的組件組成視圖。不要?jiǎng)?chuàng)建混雜著布局和功能的一次性組件
// bad class PeopleWrappedInBSRow extends React.Component { render () { return (); } }
// good class BSRow extends React.Component { render () { return容器組件(有狀態(tài)組件){this.props.children}; } } class SomeView extends React.Component { render () { return (); } }
容器組件負(fù)責(zé)獲取數(shù)據(jù)并交付給相應(yīng)的子組件渲染,僅此而已。— Jason Bonta
// bad // CommentList.js class CommentList extends React.Component { getInitialState () { return { comments: [] }; } componentDidMount () { $.ajax({ url: "/my-comments.json", dataType: "json", success: function(comments) { this.setState({comments: comments}); }.bind(this) }); } render () { return (
//good // CommentList.js class CommentList extends React.Component { render() { return (
相關(guān)鏈接:
Container Components
React.js Conf 2015 - Making your app fast with high-performance components
不要在render中緩存狀態(tài)
// bad render () { let name = `Mrs. ${this.props.name}`; return{name}; } // good render () { return{`Mrs. ${this.props.name}`}; }
// best get fancyName () { return `Mrs. ${this.props.name}`; } render () { return{this.fancyName}; }
這里多半是出于代碼風(fēng)格的考慮,不過(guò)還是保持比較好,我懷疑也可能跟性能有關(guān)。
復(fù)合條件不要把復(fù)合條件判斷放在render里。
// bad render () { return{if (this.state.happy && this.state.knowsIt) { return "Clapping hands" }; }
// better get isTotesHappy() { return this.state.happy && this.state.knowsIt; }, render() { return{(this.isTotesHappy) && "Clapping hands"}; }
這里最好的解決方案是使用容器組件來(lái)管理你的狀態(tài)然后在通過(guò)屬性(props)往下層傳遞。
檢查空值不要去檢查是否存在某個(gè)prop值,快使用defaultProps。
// bad render () { if (this.props.person) { return{this.props.person.firstName}; } else { return null; } }
// good class MyComponent extends React.Component { render() { return{this.props.person.firstName}; } } MyComponent.defaultProps = { person: { firstName: "Guest" } };
當(dāng)你的值是對(duì)象或者數(shù)組時(shí),使用 PropTypes.shape聲明嵌套數(shù)據(jù)的預(yù)期類型。
通過(guò)Props設(shè)置State不要通過(guò)props值去設(shè)置state,除非明顯是個(gè)初始值。
// bad getInitialState () { return { items: this.props.items }; }
// good getInitialState () { return { items: this.props.initialItems }; }
詳細(xì)請(qǐng)閱讀官網(wǎng)的Props in getInitialState Is an Anti-Pattern
命名事件響應(yīng)方法// bad punchABadger () { /*...*/ }, render () { return ; }
// good handleClick () { /*...*/ }, render () { return ; }
處理方法的命名必須:
第一個(gè)單詞為handle
最后一個(gè)單詞為要響應(yīng)的事件(比如Click,Change)
現(xiàn)在時(shí)態(tài)
如果為了避免命名沖突,你可以在handle和事件名中間加入其他信息。比如,你可以定義handleNameChange 和handleAgeChange來(lái)區(qū)分onChange的不同響應(yīng)處理。不過(guò)當(dāng)你這樣做的時(shí)候,你要問(wèn)問(wèn)自己是否需要一個(gè)新的組件了。
可以使用自定義事件替代預(yù)設(shè)的事件名。
class Owner extends React.Component { handleDelete () { // handle Ownee"s onDelete event } render () { return使用PropTypes; } } class Ownee extends React.Component { render () { return ; } } Ownee.propTypes = { onDelete: React.PropTypes.func.isRequired };
使用PropTypes可以預(yù)先定義屬性的類型,可以在之后獲得一些有意義的警告信息。
MyValidatedComponent.propTypes = { name: React.PropTypes.string };
MyValidatedComponent的name屬性值如果不是string類型的話, 會(huì)輸出警告。
// Warning: Invalid prop `name` of type `number` supplied to `MyValidatedComponent`, expected `string`.
在這里也可以設(shè)置屬性是否是必須存在的。
MyValidatedComponent.propTypes = { name: React.PropTypes.string.isRequired }
這個(gè)組件會(huì)驗(yàn)證是否存在name屬性。
// Warning: Required prop `name` was not specified in `Person`
相關(guān)鏈接:Prop Validation
使用特殊符號(hào)要在使用React中使用特殊符號(hào),請(qǐng)使用String.fromCharCode()。
// badPiCO · Mascot// nopePiCO · Mascot// good{"PiCO " + String.fromCharCode(183) + " Mascot"}// better{`PiCO ${String.fromCharCode(183)} Mascot`}
相關(guān)鏈接:HTML Entities
Tables瀏覽器認(rèn)為你是愚蠢的,但是React不這么人為。請(qǐng)始終為你的table組件添加tbody。
// bad render () { return (
瀏覽器會(huì)自動(dòng)插入tbody當(dāng)你忘了寫它。React則不會(huì),這樣會(huì)給你的代碼帶來(lái)混亂,請(qǐng)記住使用tbody。
classnames使用classNames管理你的classes邏輯。
// bad get classes () { let classes = ["MyComponent"]; if (this.state.active) { classes.push("MyComponent--active"); } return classes.join(" "); } render () { return ; }
// good render () { let classes = { "MyComponent": true, "MyComponent--active": this.state.active }; return ; }
相關(guān)鏈接:Class Name Manipulation
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://m.hztianpu.com/yun/80179.html
摘要:原文鏈接高階組件在中是組件復(fù)用的一個(gè)強(qiáng)大工具。在本文中,高階組件將會(huì)被分為兩種基本模式,我們將其命名為和用附加的功能來(lái)包裹組件。這里我們使用泛型表示傳遞到的組件的。在這里,我們定義從返回的組件,并指定該組件將包括傳入組件的和的。 原文鏈接:https://medium.com/@jrwebdev/... 高階組件(HOCs)在React中是組件復(fù)用的一個(gè)強(qiáng)大工具。但是,經(jīng)常有開(kāi)發(fā)者在...
摘要:更新日志應(yīng)對(duì)添加以編程方式收集性能測(cè)量。在和在將棄用為常見(jiàn)攻擊面。添加對(duì)事件的支持。在從調(diào)用時(shí)發(fā)出警告,創(chuàng)建循環(huán)。在和從錯(cuò)誤的渲染器使用時(shí)發(fā)出警告。 2019年8月8日,我們發(fā)布了React 16.9。它包含幾個(gè)新功能,錯(cuò)誤修正和新的棄用警告,以幫助準(zhǔn)備未來(lái)的主要版本。 showImg(https://segmentfault.com/img/bVbwoB5?w=1728&h=666)...
摘要:更新日志應(yīng)對(duì)添加以編程方式收集性能測(cè)量。在和在將棄用為常見(jiàn)攻擊面。添加對(duì)事件的支持。在從調(diào)用時(shí)發(fā)出警告,創(chuàng)建循環(huán)。在和從錯(cuò)誤的渲染器使用時(shí)發(fā)出警告。 2019年8月8日,我們發(fā)布了React 16.9。它包含幾個(gè)新功能,錯(cuò)誤修正和新的棄用警告,以幫助準(zhǔn)備未來(lái)的主要版本。 showImg(https://segmentfault.com/img/bVbwoB5?w=1728&h=666)...
摘要:我的教程可能也會(huì)幫你一把其他的二分法展示型組件和容器型組件這種分類并非十分嚴(yán)格,這是按照它們的目的進(jìn)行分類。在我看來(lái),展示型組件往往是無(wú)狀態(tài)的純函數(shù)組件,容器型組件往往是有狀態(tài)的純類組件。不要把展示型組件和容器型組件的劃分當(dāng)成教條。 本文譯自Presentational and Container Components,文章的作者是Dan Abramov,他同時(shí)也是Redux和Crea...
摘要:正在失業(yè)中的課多周刊第期我們的微信公眾號(hào),更多精彩內(nèi)容皆在微信公眾號(hào),歡迎關(guān)注。若有幫助,請(qǐng)把課多周刊推薦給你的朋友,你的支持是我們最大的動(dòng)力。是一種禍害譯本文淺談了在中關(guān)于的不好之處。淺談超時(shí)一運(yùn)維的排查方式。 正在失業(yè)中的《課多周刊》(第3期) 我們的微信公眾號(hào):fed-talk,更多精彩內(nèi)容皆在微信公眾號(hào),歡迎關(guān)注。 若有幫助,請(qǐng)把 課多周刊 推薦給你的朋友,你的支持是我們最大的...
閱讀 1952·2021-09-28 09:36
閱讀 2518·2021-09-08 09:35
閱讀 3122·2019-08-30 15:53
閱讀 1608·2019-08-30 14:08
閱讀 727·2019-08-29 18:40
閱讀 2915·2019-08-29 13:57
閱讀 2757·2019-08-29 13:55
閱讀 747·2019-08-26 13:45