如何防止页面刷新/视图更改后 React 中的状态发生变化?

问题描述 投票:0回答:2

我的 onClick 事件处理程序向数据库字段添加/删除 id,并根据切换状态 true/false 更改按钮颜色。 虽然数据更新工作正常,但颜色状态会在页面刷新/视图更改时重置。 我猜想状态需要通过回调函数传递(在这种情况下是子对父的关系),但我不确定。

我认为有必要在 LocalStorage 中“保留”当前状态,但这并没有解决问题。虽然 LocalStorage 值“true”和“false”保持其状态(如控制台中显示),但刷新页面时按钮的颜色仍会重置。

我附上了对评估该问题可能很重要的代码部分:

// initialization of toggle state
let toggleClick = false;

...

 this.state = {
      fav: props.favorite
    };
    this.toggleClass = this.toggleClass.bind(this);
  }

...

componentDidUpdate(prevProps) {
    if (this.props.favorite !== prevProps.favorite) {
      this.setState({
        fav: this.props.favorite
      });
    }
  }

  toggleClass() {
    toggleClick = true;
    if (!this.state.fav) {
      this.addId(this.props.movie._id);
    } else {
      this.removeId();
    }
  }

...

<span
  onClick={() => this.toggleClass()}
  className={this.state.fav ? "favme active" : "favme"}
>&#x2605;</span>
reactjs local-storage refresh setstate
2个回答
0
投票

我的 React 应用程序也遇到了同样的问题。为此,我总是使用

componentDidMount
,因为它是在渲染后立即调用的。但是,如果您调用
setState
函数,它将自动调用渲染,因此您的更改将会出现。如果刷新页面,状态将重置为默认值。因此,实现这一目标的最佳方法是:

componentDidMount() {
   const getDbAnswer = //fetch a signal from the db
   if (getDBAnswer === true) {
     this.setState({ fav: true })
   else
     this.setState({ fav: false })
}

您甚至可以使用 localStorage 设置变量。请记住,localStorage 仅接受

string
值,不接受
boolean

componentDidMount() {
  const getDbAnswer = //fetch a signal from the db
  if (getDBAnswer === true)
    localStorage.setItem("fav", "true");
  else
    localStorage.setItem("fav", "false");
}

然后你就可以像这样使用它:

<div className={localStorage.getItem("fav") === "true" ? "favme active" : "favme"}>

0
投票

刷新视图时我遇到了类似的问题。这是因为组件在补水完成之前渲染。我通过使用 Redux Persist 解决了我的问题。我们可以使用 Redux Persist 来延迟渲染,我将 persistStore 放在我的主组件中:

componentWillMount() {
  persistStore(store, {}, () => {
  this.setState({rehydrated: true})
  })
}

这将确保当存储重新水化时组件重新渲染。

https://github.com/rt2zz/redux-persist

© www.soinside.com 2019 - 2024. All rights reserved.