Some Tips on React

用了大約兩天時(shí)間,第三次閱讀了 React 的 Docs,整理出一些之前沒有注意到的 React 的語(yǔ)法與使用原則。隨后會(huì)附上 Sample Code & Translation.

  1. this.props.children returns nested elements in this element.
    this.props.children 返回 this 中的嵌套標(biāo)簽。

  2. md.render(this.props.children.toString()) converts markdown to HTML Elements. (Plugin: Remarkable)
    md.render(this.props.children.toString()) 可以將 Markdown 轉(zhuǎn)換成 HTML 標(biāo)簽。

  3. JSX prevents injection attacks. It's safe to embed user input in JSX.
    JSX 具備注入保護(hù)功能。在 JSX 中嵌入用戶輸入是安全的。

  4. All React Components must act like pure functions with respect to their props.
    所有的 React 組件 必須表現(xiàn)的像純函數(shù),并與其屬性( props )關(guān)聯(lián)。

  5. Class components should always call the base constructor with props.
    類組件必須調(diào)用基本構(gòu)造函數(shù) constructor 并傳入 props 參數(shù)。

    class Clock extends React.Component {
        constructor(props) {
            super(props);
            this.state = {date: new Date()};
        }
        render() {
            return (
                <div>
                    <h1>Hello World!</h1>
                    <h2>It's {this.state.date.toLocaleTimeString()}.</h2>
                </div>
            );
        }
    }
    
  6. Lifecycle Hooks(生命周期鉤子):

    • Pay attention to componentWillUnmount.
      注意合理使用 componentWillUnmount 函數(shù)。(比如解除計(jì)時(shí)器任務(wù))
  7. If something is not used in render(), it SHOULD NOT be in state.
    render() 函數(shù)中用不到的東西,不應(yīng)該出現(xiàn)在 state 里。

  8. this.props or this.state may be updated asynchronously, DO NOT rely on their values for calculating the next state.
    this.props 或者 this.state 可能會(huì)被異步更新,所以不要通過(guò)他們的值來(lái)計(jì)算下一個(gè)狀態(tài)的值。

    • One way to meet this need: Use a second form of setState() that accepts a function rather than an object.
      一種符合需求的方法:使用 setState() 的第二種形式,它接收一個(gè)函數(shù)參數(shù)而不是一個(gè)對(duì)象。

      this.setState((prevState, props) => ({
          counter: prevState.counter + props.increment
      }));
      
  9. React's Data Flow( React 的數(shù)據(jù)流):

    • "Top-Down" or "Unidirectional"
      自頂向下 / 單向數(shù)據(jù)流
    • Children don't know where data come from.
      子元素并不知道數(shù)據(jù)的來(lái)源。
  10. You CANNNOT return false to prevent default behavior in React. You MUST call preventDefault() explicitly.
    在 React 中,不能通過(guò)返回 false 來(lái)阻止默認(rèn)行為。必須顯式地調(diào)用 preventDefault()函數(shù)。

    // Wrong
    <a href="#" onclick="console.log('The link was clicked.'); return false">
        Click me
    </a>
    
    // Right
    function ActionLink() {
        function handleClick(e) {
            e.preventDefault();
            console.log('The link was clicked.');
        }
        return (
            <a href="#" onClick={handleClick}>
            Click me
            </a>
        );
    }
    
  11. "this Binding" is necessary to make this work in the callback.
    this 綁定”的目的是使 this 在回調(diào)函數(shù)中能正常工作。

    • this.handleClick = this.handleClick.bind(this)

    • In JavaScript, class methods are not bound by default.
      在 JavaScript 中,類方法默認(rèn)不會(huì)綁定。

    • Fix 1: Property Initializer 屬性初始化

      handleClick = () => {
          console.log('this is:', this);
      }
      
    • Fix 2 (Not Recommend): Arrow Function 箭頭函數(shù)

      class LoggingButton extends React.Component {
          handleClick() {
              console.log('this is:', this);
          }
      
          render() {
          // This syntax ensures `this` is bound within handleClick
              return (
                  <button onClick={(e) => this.handleClick(e)}>
                      Click me
                  </button>
              );
          }
      }
      
      • The problem with this syntax is that a different callback is created each time the LoggingButton render. If this callback is passed as a prop to lower components, those components might do an extra re-rendering.
  12. use if conditions to render part of the component.
    使用 if 條件語(yǔ)句控制組件渲染。

    // One Special Format: if statement in JSX
    render() {
      const isLoggedIn = this.state.isLoggedIn;
      return (
        <div>
          {isLoggedIn ? (
            <LogoutButton onClick={this.handleLogoutClick} />
          ) : (
            <LoginButton onClick={this.handleLoginClick} />
          )}
        </div>
      );
    }
    
  13. return null to hide a component. (Combined with state)
    通過(guò)返回 null 隱藏一個(gè)組件。

  14. A key should be provided for list items.
    列舉元素時(shí),應(yīng)當(dāng)為每一個(gè)元素提供一個(gè) key

    • keys help React identify which items have changed, are added, or are removed. keys should be given to the elements inside the array to give the elements a stable identity.
      key可以幫助 React 識(shí)別哪一個(gè)元素被改動(dòng)、被添加或者被刪除了。 key 應(yīng)該被置于數(shù)組內(nèi)的標(biāo)簽中,以此提供一個(gè)穩(wěn)定的標(biāo)識(shí)。
    const content = props.posts.map((post) =>
        <div key={post.id}>
            <h3>{post.title}</h3>
            <p>{post.content}</p>
        </div>
    );
    
  15. keys MUST ONLY be unique among siblings.
    key在兄弟標(biāo)簽之間必須是唯一的。

  16. keys don't get passed to your components.
    key 屬性不會(huì)傳遞給組件。

    • To pass them, you need to create a new prop with another name.
      新建一個(gè)其它名字的屬性保存 key 的值以傳遞它。
  17. In React, a <textarea> uses a value attribute to get the content instead of HTML's children.
    在 React 中,<textarea> 使用 value 屬性而不是 HTML 提供的 children 屬性獲取內(nèi)容。

  18. Instead of use selected attribute on <option>, React use value on <select> to initial selected item.
    React 通過(guò)初始化 <select>value 屬性來(lái)指定初始的選中元素,而不是使用 <option>selected 屬性。

    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <label>
                Pick your favorite La Croix flavor:
                    <select value={this.state.value} onChange={this.handleChange}>
                        <option value="grapefruit">Grapefruit</option>
                        <option value="lime">Lime</option>
                        <option value="coconut">Coconut</option>
                        <option value="mango">Mango</option>
                    </select>
                </label>
                <input type="submit" value="Submit" />
            </form>
        );
    }
    
  19. When you need to handle multiple controlled input elements, you can add a name attribute to each element and let the handler function choose what to do based on the value of event.target.name.

  20. setState() will automatically merges a partial state into the current state.
    setState() 函數(shù)會(huì)自動(dòng)將部分狀態(tài)與當(dāng)前狀態(tài)合并。

  21. If something can be derived from either props or state, it probably shouldn't be in the state.
    如果某些元素既可以放在 props 里又可以放在 state 里,那么它不應(yīng)當(dāng)被放在 state 里。

  22. DONOT use state at all to build static version of your app for it's reserved only for interactivity.
    構(gòu)建應(yīng)用的靜態(tài)版本時(shí)不應(yīng)當(dāng)使用 state,因?yàn)?state 是用來(lái)實(shí)現(xiàn)交互的。

  23. Figure out the absolute minimal representation of the state your app needs and compute everything else you need on-demand.
    找出應(yīng)用的最小狀態(tài)代表,并計(jì)算一切其它需要的值。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,983評(píng)論 6 537
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,772評(píng)論 3 422
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人,你說(shuō)我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,947評(píng)論 0 381
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,201評(píng)論 1 315
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,960評(píng)論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,350評(píng)論 1 324
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,406評(píng)論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,549評(píng)論 0 289
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,104評(píng)論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,914評(píng)論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,089評(píng)論 1 371
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,647評(píng)論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,340評(píng)論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,753評(píng)論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,007評(píng)論 1 289
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,834評(píng)論 3 395
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,106評(píng)論 2 375

推薦閱讀更多精彩內(nèi)容