【问题标题】:How to persist state in react class component for UI when I navigate or refresh the page导航或刷新页面时如何在 UI 的反应类组件中保持状态
【发布时间】:2021-04-18 14:35:35
【问题描述】:

我正在尝试保存存储在状态中的选择,并且即使在页面导航之后也保存它。我看到使用本地存储可以做到这一点,这对我来说是首选方式。但是,我在功能组件中看到了很多资源,但对于类组件却没有。所以我试了一下,但它甚至没有做任何事情,仍然没有保存选择。

背景:,我有一个状态listView,要么是真要么是假。因此,如果 listView 为 true,则视图将是 listView。如果我将其切换为 false,并刷新页面,listView 布尔值再次变为 true。当我导航到另一个页面时也是如此。

这是我的状态:(实施后)

this.state = {
      listView: JSON.parse(localStorage.getItem('listView')) || []
    };

这里是选择的处理程序(实现后):

  renderListView = (selection) => {
    this.setState({
    listView: selection
  },() => {
    localStorage.setItem('listView', JSON.stringify(this.state.listView))
  });
  }

这就是我调用它的地方。以防万一您需要查看:

   <ToggleButtonGroup className={classes.toggleButtonContainer} exclusive orientation="horizontal">
            <ToggleButton className={listView ? classes.selectedToggleButton : '' } selected={listView} onClick={() => this.renderListView(true)} value="list" aria-label="list">
               <Icon fontSize="large" color="default">view_list</Icon>
            </ToggleButton>
            <ToggleButton className={!listView ? classes.selectedToggleButton : '' } selected={!listView} onClick={() => this.renderListView(false)} value="module" aria-label="module">
                <Icon fontSize="large" color="default">view_module</Icon>
            </ToggleButton>
        </ToggleButtonGroup>

【问题讨论】:

    标签: javascript json reactjs react-native local-storage


    【解决方案1】:

    你可以使用componentDidMount()

    componentDidMount() {
     const listView = localStorage.getItem('listView')==='true';
      this.setState({listView});
    }
    

    如果这不起作用,您可以将您的代码添加到 codeSandbox,以便我可以了解确切的问题是什么

    【讨论】:

      【解决方案2】:

      主要问题是你的初始化:

      JSON.parse(localStorage.getItem('listView')) || []
      

      如果该值存储为false,那么对于|| 运算符,它被认为是虚假的,因此使用第二个操作数[]。您可以使用 ?? 而不是 || 来检查空值(nullundefined)而不是虚假值(nullundefinedfalse0、@987654335 @, NaN)。

      JSON.parse(localStorage.getItem('listView')) ?? []
      

      如果"listView" 尚未在本地存储中设置,则返回null 并且JSON.parse(null) 也将评估为null。在这种情况下使用默认值。

      // when loading from local storage
      false || [] //=> []
      false ?? [] //=> false
      
      // if local storage is not set
      null || [] //=> []
      null ?? [] //=> []
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-01
        • 2018-07-25
        • 2021-09-27
        • 2022-08-22
        • 1970-01-01
        • 2012-09-25
        • 2019-05-19
        • 2019-01-30
        相关资源
        最近更新 更多