若是返回數組必須給每個數組元素添加一個惟一標識key,可是從v16.2開始reatreact
// 第一種返回數組 render() { // 這裏不一樣於v15.x必需要一個標籤來包裹 return [ // key是必須的,通常不要把數組的index索引做爲key,這樣可能會致使頁面不會按照你想象的效果進行渲染 <li key="A">First item</li>, <li key="B">Second item</li>, <li key="C">Third item</li>, ]; } // 第二種返回字符串 render() { return 'Look ma, no spans!'; }
以前react在渲染過程當中或者是生命週期內出現了致命的錯誤,react會從根組件上把全部的組件都卸載下來,以防止展示錯誤的數據,但這不是最好的用戶體驗。React 16修復了這一點,引入了Error Boundary的概念,中文譯爲「錯誤邊界」,當某個組件發生錯誤時,咱們能夠經過Error Boundary捕獲到錯誤並對錯誤作優雅處理。(注:它並不能捕獲runtime全部的錯誤,好比組件回調事件裏的錯誤,能夠把它想象成傳統的try-catch語句)api
class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } // 新增了componentDidCatch這個生命週期函數,它能夠捕獲自身及子樹上的錯誤並對錯誤作優雅處理,包括上報錯誤日誌、展現出錯提示,而不是卸載整個組件樹。 componentDidCatch(error, info) { // 錯誤代理組件的展現與否 this.setState({ hasError: true }); // 在這裏咱們能夠對錯誤進行記錄 logErrorToMyService(error, info); } render() { if (this.state.hasError) { // 在這裏咱們能夠書寫本身想要展現的ui組件 return <h1>Something went wrong.</h1>; } return this.props.children; } }
上面的組件是當頁面中有錯誤時咱們想要展現的效果,具體用法以下:數組
render(){ return ( <div> <ErrorBoundary> // 外層組件咱們定義的錯誤組件 <Profile user={this.state.user} /> // 內層組件是咱們將要監視的自定義組件 </ErrorBoundary> <button onClick={this.onClick}>Update</button> </div> ) }
以前的setState無論傳入什麼只要調用了這麼方法就會渲染服務器
selectCity(e){ const newValue = e.target.value; this.setState((state)=>{ if(state.city===newValue){ return null; } return {city:newValue} }) )