2 回答

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超9個(gè)贊
您不應(yīng)該在 render 中調(diào)用 switch 函數(shù),因?yàn)樗赡軙?huì)導(dǎo)致您的組件陷入無限循環(huán) - 每次渲染時(shí),狀態(tài)都會(huì)發(fā)生變化......它會(huì)再次渲染。
此外,在一個(gè)函數(shù)中混合渲染和狀態(tài)更新是非常危險(xiǎn)的 -永遠(yuǎn)不應(yīng)該這樣做,因?yàn)樗赡軙?huì)導(dǎo)致大量?jī)?yōu)化泄漏。
將您的函數(shù)調(diào)用移動(dòng)到另一個(gè)方法,例如componentDidMount():
class MyClass extends React.Component {
constructor(props) {
super(props);
this.state = {myStr: "Initial state"};
}
componentDidMount() {
switchFunc();
}
switchFunc = () => {
switch (1 + 3) {
case 2 + 2:
this.setState({ myStr: "Yes its four!"});
break;
default:
this.setState({ myStr: "Oops! default"});
}
}
render(){
return (
<div>
<h1>Hello, world!</h1>
<div>
<h3>{this.state.myStr}</h3>
</div>
</div>
);
}
}
ReactDOM.render(
<MyClass />,
document.getElementById('root')
);
componentDidMountrender是由 React 提供的一種特殊方法 (as ),它允許在安裝組件時(shí)控制組件的行為。更多關(guān)于這些方法的信息:https ://reactjs.org/docs/state-and-lifecycle.html
另外,請(qǐng)注意,暫時(shí)將渲染 myStr 與render方法分開是一種過大的殺傷力 - 就像render我的示例一樣,直接在方法中使用它。
只是一個(gè)旁注 - 嘗試camelCased為您的方法使用名稱,以使它們與其余代碼保持一致(如我更新的示例中所示)。
關(guān)于綁定的另一個(gè)優(yōu)化信息-您添加.bind()了對(duì)構(gòu)造函數(shù)的調(diào)用-不需要,因?yàn)槟鷖witchFunc沒有在類之外的任何上下文中使用(因此,它this始終指向類,因此您不需要.bind()再次訪問上下文) . 此外,更重要的是——你把它寫成一個(gè) lambda ( () => {}) 函數(shù),而不是一個(gè)普通函數(shù)——lambdas 沒有它們的上下文并從它們定義的地方繼承父上下文——因此它總是指向類this上下文而沒有任何顯式綁定

TA貢獻(xiàn)2019條經(jīng)驗(yàn) 獲得超9個(gè)贊
您只需通過在末尾添加括號(hào)來調(diào)用該函數(shù)。這將導(dǎo)致無限循環(huán),盡管每次您的組件渲染時(shí),它都會(huì)更新狀態(tài),這反過來又會(huì)導(dǎo)致重新渲染等等。
class MyClass extends React.Component {
constructor(props) {
super(props);
this.state = { myStr: "Initial state" };
this.switch_func = this.switch_func.bind(this);
}
switch_func = () => {
switch (1 + 3) {
case 2 + 2:
this.setState({ myStr: "Yes its four!" });
break;
default:
this.setState({ myStr: "Oops! default" });
}
return (
<div>
<h3>{this.state.myStr}</h3>
</div>
);
}
render() {
return (
<div>
<h1>Hello, world!</h1>
{this.switch_func()}
</div>
);
}
}
ReactDOM.render(
<MyClass />,
document.getElementById('root')
);
添加回答
舉報(bào)