首页 > 解决方案 > 重新加载页面后如何保持显示值?

问题描述

我有一个 React.js 应用程序,它连接并订阅了一个 MQTT 代理。最初,它正确地从代理获取值,但是如果我重新加载页面,它首先显示 0,然后它必须等待从代理再次接收到该值,因此在订阅之前它不会获得其实际值是通知更改。

我想要的是重新加载页面后,我仍然可以看到之前的值。我怎样才能做到这一点?

提前致谢。

这是我的代码:

  render() {

     //access range from redux store via props
     const {rangeEstimate} = this.props
     //if range is not null - show it, otherwise - show no data
    const rangeValue = rangeEstimate && rangeEstimate>=0 ? 
      (<div>
        {rangeEstimate.toString()}
      </div>)
      : (<div>0</div>)


if(rangeEstimate>=0 && rangeEstimate) {
    localStorage.setItem('rangeValue', rangeEstimate);
 
}

const {battery} = this.props
//if battery is not null - show it, otherwise - show no data
const batteryValue = battery && battery>=0 ? 
(<div>
   {battery +"%"}
 </div>)

: (<div>0%</div>)

       return (
           <StyledRangeContainer className="RANGE">
                    <div>
                    <StyledRangeText>{rangeValue}</StyledRangeText>
                    </div>
                    <StyledBatteryCapacityValue>{batteryValue}</StyledBatteryCapacityValue>
            </StyledRangeContainer>
          );
    }
}
    //map this component's state to props from redux store
    const mapStateToProps = (state) => {
    return {
        rangeEstimate:state.rangeEstimate,
        battery:state.battery
    }
 
}


//connect this component to Redux
export default connect(mapStateToProps,null) (RangeEstimate)

标签: reactjsreduxmqtt

解决方案


假设您可以控制 MQTT 发布者,请发布设置了保留位的值。

这意味着当客户端订阅该主题时,最后发布的值将立即由代理传递。下一个发布的消息(带有保留位)将替换这个存储的值。


推荐阅读