我正在使用 React 并從 Material UI 渲染一個模態。模態的呈現方式是它必須是代碼體的一部分。所以我把它添加到頁面底部。狀態決定模態是否打開。問題是我可以看到模態中的函式被多次呼叫。而且非常迅速。就像每秒不止一次。請看我的代碼:
class ComponentName extends React.Component {
constructor(props) {
super(props);
this.state = {
countries: [],
isButtonDisabled: false,
formError: false,
showModalCta: false,
showModal: false,
iframeUrl: ''
};
}
handleClose = () => {
this.setState({
showModal: false
});
};
handleShowModal = () => {
this.setState({
showModal: true
})
}
showModalContent = () => {
const { classes } = this.props;
const { iframeUrl } = this.state;
getiframeUrl().then((res) => {
this.setState({
iframeUrl: res.level2VerificationUrl
});
});
return (
<Paper className={classes.modalPaper}>
<iframe src={iframeUrl} width="500px" height="500px" />
</Paper>
);
};
render() {
const {
classes, history, firstName, lastName, country, region, address, city, dob, phone, smsCode, postalCode, actions
} = this.props;
const {
countries, formError, isButtonDisabled, showCta, showModal
} = this.state;
return (
<div>
<Modal className={classes.modal} open={showModal} onClose={this.handleClose}>
{this.showModalContent()}
</Modal>
</div>
);
}
}
它幾乎每秒呼叫該函式以獲取 url。但我不太明白為什么這是這種行為。一直在研究這個,但沒有答案。有什么辦法可以防止這種情況嗎?謝謝!
uj5u.com熱心網友回復:
showModalContent 將在組件的每次“狀態更改”(在每次渲染時)執行。在那里(從我看到的)你正在呼叫一個承諾(getiframeUrl)并且你正在設定組件的狀態(這使它改變狀態)。
因此:渲染 -> showModalContent -> 更改狀態 -> 重新渲染 -> showModalContent -> ...(無限回圈)。
我的建議是您只在 componentDidMount 中執行 iframeUrl 的 setState。像這樣的東西:
componentDidMount() {
const { iframeUrl } = this.state;
getiframeUrl().then((res) => {
this.setState({
iframeUrl: res.level2VerificationUrl
});
});
}
showModalContent = () => {
const { classes } = this.props;
return (
<Paper className={classes.modalPaper}>
<iframe src={iframeUrl} width="500px" height="500px" />
</Paper>
);
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/354925.html
標籤:javascript 反应 反应原生 异步 材质-ui
上一篇:交通燈問題。單擊時切換顏色
