# 0.官方 ###### tags: `React` `Javascript` * 所有的 React component 都必須像 Pure function 一般保護他的 props Pure function : 方法內不會改變其參數 * State 的更新可能是非同步的 React 可以將多個 setState() 呼叫批次處理為單一的更新,以提高效能。 使用this.props 和 this.state可能出錯(更新的順序不一定如預期) ``` // 錯誤 this.setState({ counter: this.state.counter + this.props.increment, }); ``` 應使用 setState(()=>{}): ``` // 正確 this.setState((state, props) => ({ counter: state.counter + props.increment })); ``` * Event Handler中的this 箭頭函式綁定死事件宣告位置的物件。 若為一般function宣告方式,需要以bind()綁定物件,否則this=undefined ``` <button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button> <button onClick={this.deleteRow.bind(this, id)}>Delete Row</button> ``` * Key Key 幫助 React 分辨哪些項目被改變、增加或刪除。在 array 裡面的每個 element 都應該要有一個 key,如此才能給予每個 element 一個固定的身份 > 避免用索引作為key : 詳見哲右的筆記 ``` const todoItems = todos.map((todo, index) => <li key={index}> {todo.text} </li> ); ``` * 提升 state :上至下的資料流 在 React 應用程式中,對於資料的變化只能有一個唯一的「真相來源」。 通常來說,state 會優先被加入到需要 render 的 component。 接著,如果發現其他的 component 也需要render的話,便應該要提升 state 到共同最靠近的 ancestor。 因此,如果某樣東西可以從 prop 或 state 被取得,它可能不應該在 state。而應該將此處的statee向上提升。 > 依賴上至下的資料流,而不是嘗試在不同 component 之間同步 state。 * 用Composition (不要繼承) 1. 不確定自己將有哪些children component的父層, 可用{props.children}接收其他component傳入 2. 特別化 (似繼承extends) 更「特別」的 component render 更多「通用」的 component, 並使用 prop 對其進行設定 ``` function Dialog(props) { return ( <FancyBorder color="blue"> <h1 className="Dialog-title"> {props.title} </h1> <p className="Dialog-message"> {props.message} </p> {props.children} </FancyBorder> ); } class SignUpDialog extends React.Component { ...... render() { return ( <Dialog title="Mars Exploration Program" message="How should we refer to you?"> <input value={this.state.login} onChange={this.handleChange} /> <button onClick={this.handleSignUp}> Sign Me Up! </button> </Dialog> ); } ...... } ``` ----------------- > 總結 用react的方式思考 1. 將頁面拆解成 component 2. 建立一個靜態版本(只有render 沒有state) 3. 找出State (只有變動的資料需要設成state) 4. 找出 State 應該在哪個component a. 找出所有有依據state資料行為的component。 b. 找出共同擁有者 c. 若無component有用到state,便建立一個新的用以保存state。 並把它加到層級中共同擁有者之上的某處。