[英]How much safety logic should I include in my private components?
在構建了很多React組件,添加了propTypes,編寫了測試並添加了偶爾的默認props之后,我仍然在質疑多少安全性過高。 熟悉Flow類型之后,我開始覺得需要在嘗試呈現內容之前添加更多安全檢查,以確保所有預期數據都存在。
我可以看到的額外安全性的好處之一是,即使API失敗,也可以確保組件始終正確呈現。 另一方面,通過快速失敗可以更好地處理API失敗。 這些組件是非常內部的,它們的用法非常明確並且易於跟蹤。
當前組件:
class Example extends Component {
render() {
return this.props.items.slice(4)
.map(item => <div>{item.name}</div>);
}
}
安全的:
class Example extends Component {
render() {
return this.props.items &&
this.props.items.length &&
this.props.items.length > 3 &&
this.props.items.slice(4)
.map(item => <div>{item.name}</div>);
}
}
這是工程上的問題嗎?
是。
如果組件將接受用戶輸入,則應驗證該輸入。 因組件使用不當而導致的故障應迅速消除,以便可以在開發中進行糾正,而不會影響生產環境。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.