reactjs - 重新加载页面后如何保持显示值?
问题描述
我有一个 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 发布者,请发布设置了保留位的值。
这意味着当客户端订阅该主题时,最后发布的值将立即由代理传递。下一个发布的消息(带有保留位)将替换这个存储的值。
推荐阅读
- r - 如何在并行 bash 中运行这个简单的 for 循环?
- macos - brew安装的cartopy中缺少符号
- reactjs - 项目上的 React Hook
- postman - Assertible Postman Collection - 测试请求之间的延迟
- php - PHP 搜索过滤器。数组返回 NULL
- c++ - C++ 中的 getline 明显比 C 慢
- excel - 如何使用 Excel VBA 检查 Range 中的每个单元格是否在另一个 Range 上找到?
- keras - 应用一些增强层后,真阳性和假阳性分数下降到零
- c# - 如何通过重复按一个键将 Unity3D 中的对象从一个位置移动到另一个位置并按设定的顺序进一步移动?
- python-3.x - 无法在 NLTK 中访问下载的语料库