如何在重新加载页面后保持显示值?

How to keep value displayed after reloading of the page?

我有一个 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)

假设您可以控制 MQTT 发布者,发布带有保留位集的值。

这意味着每当客户端订阅该主题时,最后发布的值将由经纪人立即交付。下一条发布的消息(带有保留位)将替换此存储的值。

在大多数软件工程中,我们在构造函数中设置初始值或起始值。因此,让我们添加一个并在您的 class 中使用它。我假设它是 ReactJS class,因为您使用的是 render() 方法。这是您的构造函数...

constructor(props) {
    super(props);
    this.state = {
         'rangeValue':localeStorage.getItem('rangeValue'),
         'batteryValue':localeStorage.getItem('batteryValue'),
    };
}

注意我正在用 localeStorage.getItem().

的结果填充状态

然后你需要更新你的 render() 以基于状态...

   return (
       <StyledRangeContainer className="RANGE">
                <div>
                <StyledRangeText>{this.props.rangeValue ? this.props.rangeValue : this.state.rangeValue}</StyledRangeText>
                </div>
                <StyledBatteryCapacityValue>{this.props.batteryValue ? this.props.batteryValue : this.state.batteryValue}</StyledBatteryCapacityValue>
        </StyledRangeContainer>
      );

当然,如果存在道具值,您会想要使用它,因此这段代码通过检查道具反映了这一点。您可能希望它检查一个变量,但这也可以。