99re热这里只有精品视频,7777色鬼xxxx欧美色妇,国产成人精品一区二三区在线观看,内射爽无广熟女亚洲,精品人妻av一区二区三区

getInitialState 里的 Props 是一個反模式

2019-08-14 14:31 更新

注意:

這實際上不是一篇單獨的 React 提示,因為類似的反模式設(shè)計也經(jīng)常會在平時的編碼中出現(xiàn);這里,React 只是簡單清晰地指出來這個問題

使用 props, 自父級向下級傳遞,在使用 getInitialState 生成 state 的時候,經(jīng)常會導(dǎo)致重復(fù)的"來源信任",i.e. 如果有可能,請盡量在使用的時候計算值,以此來確保不會出現(xiàn)同步延遲的問題和狀態(tài)保持的問題。

糟糕的例子

var MessageBox = React.createClass({
  getInitialState: function() {    return {nameWithQualifier: 'Mr. ' + this.props.name};
  },

  render: function() {    return <div>{this.state.nameWithQualifier}</div>;
  }
});

React.render(<MessageBox name="Rogers"/>, mountNode);

Better:

更好的寫法:

var MessageBox = React.createClass({
  render: function() {    return <div>{'Mr. ' + this.props.name}</div>;
  }
});

React.render(<MessageBox name="Rogers"/>, mountNode);

(For more complex logic, simply isolate the computation in a method.)

(對于更復(fù)雜的邏輯,最好通過方法將數(shù)據(jù)處理分離開來)

然而,如果你理清了這些,那么它也就 不是 反模式了。兩者兼得不是我們的目標(biāo):

var Counter = React.createClass({
  getInitialState: function() {    // naming it initialX clearly indicates that the only purpose
    // of the passed down prop is to initialize something internally
    return {count: this.props.initialCount};
  },

  handleClick: function() {    this.setState({count: this.state.count + 1});
  },

  render: function() {    return <div onClick={this.handleClick}>{this.state.count}</div>;
  }
});

React.render(<Counter initialCount={7}/>, mountNode);


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號