3 回答

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超3個(gè)贊
setState 函數(shù)除了設(shè)置狀態(tài)外,還具有更改時(shí)重新渲染的機(jī)制。
構(gòu)造函數(shù)在組件實(shí)際安裝之前執(zhí)行,并且不會(huì)渲染任何內(nèi)容。這就是為什么在構(gòu)造函數(shù)中使用 setState 沒(méi)有意義。
所以你需要像這樣實(shí)現(xiàn)這一點(diǎn):
constructor(props) {
super(props);
this.state = {
age: '18',
id: 'name'
}
}

TA貢獻(xiàn)1846條經(jīng)驗(yàn) 獲得超7個(gè)贊
不要使用setState()內(nèi)部構(gòu)造函數(shù)或內(nèi)部渲染方法
構(gòu)造函數(shù)- 在創(chuàng)建實(shí)例時(shí)調(diào)用一次,如果您在構(gòu)造函數(shù)內(nèi)部創(chuàng)建,則不會(huì)發(fā)生重新渲染。
render - 如果您setState()在 render 方法內(nèi)部使用,它將變?yōu)闊o(wú)限,因?yàn)楫?dāng)您使用時(shí)會(huì)發(fā)生重新渲染setState()
如果你想保存這樣的屬性來(lái)聲明在生命周期方法中執(zhí)行它c(diǎn)omponentDidMount()
改進(jìn)
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
age: '18'
}
}
componentDidMount(){
this.setState({id: 'name'});
}
render(){
return (
<div>
<p>{this.state.id}</p>
<p>{this.state.value}</p>
</div>
)
}
}
或者像年齡一樣直接輸入
this.state = {
age: '18',
id: 'name'
}

TA貢獻(xiàn)1900條經(jīng)驗(yàn) 獲得超5個(gè)贊
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
age: '18',
id: '',
}
}
componentDidMount(){
this.setState({id: 'name'});
}
render(){
return (
<div>
<p>{this.state.id}</p>
<p>{this.state.age}</p>
</div>
)
}
}
添加回答
舉報(bào)