【发布时间】:2019-11-21 15:06:45
【问题描述】:
我对 React JS 很陌生,我现在正在使用它来构建一个应用程序。我有一个问题。
在按钮单击事件中,我有这样的代码逻辑:
handlestartbutton(event) {
const accesskey = localStorage.getItem(localStorageKeys.accessTokenKey);
const decodedAccessKey = jwt_decode(accesskey);
const date = dateConverter.epochToReadableDate(decodedAccessKey.exp);
if (date.currentTime < date.expiryDate) {
this.setState({
accesstokenexpirydate: true
}, () => {
if(this.state.accesstokenexpirydate === false) {
//rest of the code
}
})
在 renderer() 中我有一个这样的弹出 UI:
renderer()
{
{this.state.accesstokenexpirydate === true ? (
<Popup
open ={this.state.open}
closeOnDocumentClick={false}
closeOnEscape={false}
onClose={this.closeModal}className
>
<div className={popstyles.popupBody}>
<div className={popstyles.modalClose}>
<a className="close" onClick={this.closeModal}>
×
</a>
{""}
<div className ={popstyles.unAutherizedUser}>
<label >{homeConstantMessages.accessTokenExpire}</label>
<div className ={popstyles.unAutherizedUserMsg}>
<label>{homeConstantMessages.accessTokenExpireMsg}</label>
<button className ={styles.refreshaccessbtn} onClick = {this.navigateToHomePage.bind(this)} label = {homeConstantMessages.refreshbtn}>
</button>
</div>
</div>
</div>
</div>
</Popup>
) : (
''
)}
}
问题是当第一次单击开始按钮时,即使状态变量 accesstokenexpirydate 设置为 true,此弹出 UI 也不会弹出。当第二次点击按钮时,UI 会弹出。谁能帮帮我
【问题讨论】:
-
你能检查一下
this.state.open是从哪里设置为 true 的,这不是导致问题的原因吗? -
你能在你的代码中加入 2 个控制台日志吗?在
if (date.currentTime < date.expiryDate) {之后可以登录console.log('setting exp to true')并重新渲染:console.log('in re render:',this.state.accesstokenexpirydate,this.state.accesstokenexpirydate===true) -
@RahulJain。你是对的 this.state.open 被设置为 true 并且这导致了问题。
-
@HarshithR 您是否确定了状态设置为 true 的位置?我会将我的评论作为答案,以便您将其标记为正确。