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

时间:2019-06-06 08:06:02

标签: reactjs local-storage refresh setstate

我的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>

2 个答案:

答案 0 :(得分:0)

我的React Apps遇到了同样的问题。为此,我总是使用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"}>

答案 1 :(得分:0)

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

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

这将确保在商店重新水化后重新渲染组件。

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

相关问题