首页 > 解决方案 > 如何在反应中访问页面刷新时的状态值?

问题描述

我正在我的项目中实施时间跟踪器。当我启动我的跟踪器时,我将此跟踪器值存储到状态中,并在暂停此跟踪器时将该值更改为状态。但是当我刷新页面时,我没有得到最后更新的状态值。那么如何在页面刷新时获取状态值呢?

const React = require("react");
const ms = require("pretty-ms");

class TaskTimer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      time: 0,
      isOn: false,
      start: 0
    };
    this.startTimer = this.startTimer.bind(this);
    this.stopTimer = this.stopTimer.bind(this);
    this.resetTimer = this.resetTimer.bind(this);
  }

  startTimer() {
    this.setState({
      isOn: true,
      time: this.state.time,
      start: Date.now() - this.state.time
    });
    this.timer = setInterval(
      () =>
        this.setState({
          time: Date.now() - this.state.start
        }),
      1
    );
  }
  stopTimer() {
    this.setState({ isOn: false });
    clearInterval(this.timer);
  }
  resetTimer() {
    this.setState({ time: 0, isOn: false });
  }
  render() {
    let start =
      this.state.time == 0 ? (
        <button onClick={this.startTimer}>start</button>
      ) : null;
    let stop =
      this.state.time == 0 || !this.state.isOn ? null : (
        <button onClick={this.stopTimer}>stop</button>
      );
    let resume =
      this.state.time == 0 || this.state.isOn ? null : (
        <button onClick={this.startTimer}>resume</button>
      );
    let reset =
      this.state.time == 0 || this.state.isOn ? null : (
        <button onClick={this.resetTimer}>reset</button>
      );
    return (
      <div>
        <h3>timer: {ms(this.state.time)}</h3>
        {start}
        {resume}
        {stop}
        {reset}
      </div>
    );
  }
}
module.exports = TaskTimer;

任何人请建议我如何在页面刷新时获得状态值?

标签: reactjsmaterial-uinext.js

解决方案


如果您希望您的状态在刷新后保持不变,那么您需要将状态存储在 localStorage 中componentWillUnmount,然后将状态重置为以前的状态componentDidMount。那是

componentDidMount() {
  const stateObject = JSON.parse(localStorage.getItem("state"));
  this.setState(stateObject); 
}

componentWillUnmount() {
  localStorage.setItem("state", JSON.stringify(this.state));
}

但是,如果在刷新期间无法调用 componentWillUnmount,这可能会产生意想不到的结果。因此,一种更健壮(但性能较低)的方法是在每次更新状态时将状态更新为 localStorage。这可以通过将代码放入componentDidUpdate.

componentDidUpdate(prevProps, prevState) {
  if(prevState != this.state) {
    localStorage.setItem("state", this.state);
  }
}

更新:

经过一些研究,我发现该事件beforeunload可以以相当高效的方式工作。

  onUnload = (event) => {
    localStorage.setItem("state", JSON.stringify(this.state)
  }

  componentDidMount() {
    window.addEventListener("beforeunload", this.onUnload)
  }

  componentWillUnmount() {
    window.removeEventListener("beforeunload", this.onUnload)
  }

但是,请记住 onbeforeunload 在某些浏览器中没有正确实现(例如 iOS 中的 Safari)。因此,您可能会面临一些与此相关的问题。这是事件的兼容性列表https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload#Browser_compatibility


推荐阅读