如何在 react-redux 中调用页面刷新的函数?

Posted

技术标签:

【中文标题】如何在 react-redux 中调用页面刷新的函数?【英文标题】:how to call a function on page refresh in 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 中,并在您的页面再次打开时加载它。您可以在您的主应用程序中执行此操作 【参考方案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 操作,该操作将适当地更新商店。

【讨论】:

以上是关于如何在 react-redux 中调用页面刷新的函数?的主要内容,如果未能解决你的问题,请参考以下文章

刷新后 React-Redux 状态丢失

如何重置 react-redux 的值?

如何在flutter中调用函数后刷新页面?

如何使用 thunk 在 react-redux 挂钩中进行异步调用?

键盘输入时,如何在Ajax调用URL更改后停止MVC页面刷新

如何使用 react-redux 将错误 500 全局重定向到页面