【问题标题】:State is not upating in renderer() componentrender() 组件中的状态未更新
【发布时间】: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}>
        &times;
        </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 &lt; 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 的位置?我会将我的评论作为答案,以便您将其标记为正确。

标签: node.js reactjs electron


【解决方案1】:

1)我认为你必须应用如下箭头功能,然后你可以使用 this

handlestartbutton=(event)=> {...}

2) 我对这个名字很困惑,你不认为它应该是render(...) 而不是renderer()

【讨论】:

  • 我确信当它是一个绑定问题时,它会产生错误并且不会设置任何状态。也许 OP 在构造函数中绑定,所以箭头函数无法解决它。
猜你喜欢
  • 1970-01-01
  • 2020-10-14
  • 1970-01-01
  • 1970-01-01
  • 2021-06-15
  • 1970-01-01
  • 2022-07-16
相关资源
最近更新 更多