Some Tips on React

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

  1. this.props.children returns nested elements in this element.
    this.props.children 返回 this 中的嵌套標簽。

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

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

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

  5. Class components should always call the base constructor with props.
    類組件必須調用基本構造函數 constructor 并傳入 props 參數。

    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 函數。(比如解除計時器任務)
  7. If something is not used in render(), it SHOULD NOT be in state.
    render() 函數中用不到的東西,不應該出現在 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 可能會被異步更新,所以不要通過他們的值來計算下一個狀態的值。

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

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

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

    // 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 在回調函數中能正常工作。

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

    • In JavaScript, class methods are not bound by default.
      在 JavaScript 中,類方法默認不會綁定。

    • Fix 1: Property Initializer 屬性初始化

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

      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 條件語句控制組件渲染。

    // 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)
    通過返回 null 隱藏一個組件。

  14. A key should be provided for list items.
    列舉元素時,應當為每一個元素提供一個 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 識別哪一個元素被改動、被添加或者被刪除了。 key 應該被置于數組內的標簽中,以此提供一個穩定的標識。
    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在兄弟標簽之間必須是唯一的。

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

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

  18. Instead of use selected attribute on <option>, React use value on <select> to initial selected item.
    React 通過初始化 <select>value 屬性來指定初始的選中元素,而不是使用 <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() 函數會自動將部分狀態與當前狀態合并。

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

  22. DONOT use state at all to build static version of your app for it's reserved only for interactivity.
    構建應用的靜態版本時不應當使用 state,因為 state 是用來實現交互的。

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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容