【问题标题】:how to call a function on page refresh in react-redux?如何在 react-redux 中调用页面刷新的函数?
【发布时间】:2018-01-21 23:13:30
【问题描述】:

我正在 react-redux 中做一个应用程序,我想在页面刷新时保留我的 redux 商店,并认为不使用预定义的库,因此我将 redux 状态设置为本地状态并在 componentWillUnmount 中进行 api 调用在页面刷新时恢复 redux 状态。但它不能这样做。他们是否有任何方法可以实现这一点:

我的代码是:

componentWillMount(){
    this.setState({
        activeUser:this.props.activeUser
    })
}
componentWillUnmount(){
    this.props.loginUser(this.state.activeUser.user);
}

activeUser 是我的 redux 状态,this.props.loginUser() 进行 api 调用。我尝试使用事件处理程序:

componentDidMount(){
    window.addEventListener('onbeforeunload', this.saveStore)
}

componentWillUnmount(){
    window.removeEventListener('beforeunload', this.saveStore)
}

saveStore(){
    this.props.loginUser(this.state.activeUser.user);
}

但它对我不起作用。

【问题讨论】:

  • 我认为您不能在刷新时保留状态。您要么需要使用本地/会话存储来存储状态,要么将您的状态写入 json 文件并从那里恢复,并在刷新完成后恢复
  • 您需要做的是将商店保存在 localStorage 中,并在您的页面再次打开时加载它。您可以在您的主应用程序中执行此操作

标签: api reactjs redux


【解决方案1】:

我的理解是,您基本上想要做的是,您希望在重新加载之间保持您的应用状态(用户信息等)。

可以使用localStorage API 来实现这个效果。

我会在这里给出一种可能的解决方案。

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {activeUser: null};
  }

  componentWillMount() {
    let activeUser = localStrorage.getItem("activeUser");
    if (activeUser) {
      this.props.receivedActiveUser(JSON.parse(activeUser));
    }
  }

  componentWillReceiveProps(nextProps) {
    this.setState({activeUser: nextProps.activeUser});
  }

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

当然,您必须创建一个 receivedActiveUser 操作,该操作将适当地更新商店。

【讨论】:

    猜你喜欢
    • 2020-12-21
    • 1970-01-01
    • 2019-02-09
    • 2020-04-09
    • 1970-01-01
    • 2020-04-27
    • 1970-01-01
    • 2013-10-07
    • 2021-11-01
    相关资源
    最近更新 更多