W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
注意:
這實(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);
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: