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.
    找出应用的最小状态代表,并计算一切其它需要的值。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,591评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,448评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,823评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,204评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,228评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,190评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,078评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,923评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,334评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,550评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,727评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,428评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,022评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,672评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,826评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,734评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,619评论 2 354

推荐阅读更多精彩内容