React Context API - 在页面刷新时保留数据 [英] React Context API - persist data on page refresh

查看:41
本文介绍了React Context API - 在页面刷新时保留数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们设置了一个上下文提供程序,以及一些初始数据属性值.

Let's say we have a context provider set up, along with some initial data property values.

在某处,假设消费者然后修改了这些属性.

Somewhere along the line, let's say a consumer then modifies those properties.

在页面重新加载时,这些更改将丢失.持久化数据以便我们可以保留这些数据修改的最佳方法是什么?除了简单的本地存储之外还有其他方法吗?

On page reload, those changes are lost. What is the best way to persist the data so we can retain those data modifications? Any method other than simply local storage?

推荐答案

是的,如果您希望数据在重新加载后保持不变,您的选择将是在服务器端(通过 api 调用)或在浏览器中存储该信息存储(本地存储、会话存储、cookie).您要使用的选项取决于您希望实现的持久性级别.无论选择哪种存储方式,它都可能看起来像

Yeah, if you want the data to persist across reloads, your options are going to be storing that info server-side (via an api call) or in browser storage (local storage, session storage, cookies). The option you'll want to use depends on what level of persistence you're looking to achieve. Regardless of storage choice, it would likely look something along the lines of

const MyContext = React.createContext(defaultValue);

class Parent extends React.Component {
  setValue = (value) => {    
    this.setState({ value });
  }

  state = {
    setValue: this.setValue,
    value: localStorage.getItem("parentValueKey")
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.state.value !== prevState.value) {
      // Whatever storage mechanism you end up deciding to use.
      localStorage.setItem("parentValueKey", this.state.value)
    }
  }

  render() {
    return (
      <MyContext.Provider value={this.state}>
        {this.props.children}
      </MyContext.Provider>
    )
  }
}

这篇关于React Context API - 在页面刷新时保留数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆