【问题标题】:How to set component state conditionally如何有条件地设置组件状态
【发布时间】:2018-07-07 00:56:26
【问题描述】:

我将它作为我的主要 App 组件,它可以工作,但前提是有 localStorage 数据。

如果 localStorage 为空,我正在努力寻找一种将状态设置为空数组的方法。任何有关如何做到这一点的帮助都会非常感激!我尝试了许多不同的条件语句,但似乎都不起作用。

export default class App extends Component {
  constructor(props){
    super(props);
    // set variable as data from local storage
    const storageData = JSON.parse(localStorage.getItem('listItems'));
    console.log(storageData);

    // set initial state
      this.state = {
        value: '',
        url: '',
        // set items array as storage data variable
        // bug: Page only loads if localstorage available
        items: storageData
      }
    this.removeItem = this.removeItem.bind(this);
  }

【问题讨论】:

  • 试试这个:const storageData = (localStorage.getItem('listItems')) ? JSON.parse(localStorage.getItem('listItems')) : [];

标签: javascript reactjs local-storage


【解决方案1】:

一个简单的条件应该可以正常工作。

  this.state = {
    value: '',
    url: '',
    // If storage is not null or undefined use it,
    // otherwise use an empty array
    items: storageData || []
  }

【讨论】:

  • 如此简单!非常感谢!
【解决方案2】:

如果 listItems 在 localStorage 中尚不存在,localStorage.getItem('listItems') 将返回 null,因此您可以在解析 JSON 之前检查它。

const storageData = localStorage.getItem('listItems');
const parsedStorageData = storageData ? JSON.parse(storageData) : [];

this.state = {
  value: '',
  url: '',
  items: parsedStorageData
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-15
    • 1970-01-01
    • 2021-07-29
    • 2022-11-18
    • 2018-08-29
    • 1970-01-01
    相关资源
    最近更新 更多