getInitialState 里的 Props 是一個(gè)反模式

2019-08-14 14:31 更新

注意:

這實(shí)際上不是一篇單獨(dú)的 React 提示,因?yàn)轭愃频姆茨J皆O(shè)計(jì)也經(jīng)常會(huì)在平時(shí)的編碼中出現(xiàn);這里,React 只是簡(jiǎn)單清晰地指出來(lái)這個(gè)問(wèn)題

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

糟糕的例子

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.)

(對(duì)于更復(fù)雜的邏輯,最好通過(guò)方法將數(shù)據(jù)處理分離開(kāi)來(lái))

然而,如果你理清了這些,那么它也就 不是 反模式了。兩者兼得不是我們的目標(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)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)