【问题标题】:Setting the state in a component from localStorage从 localStorage 设置组件的状态
【发布时间】:2022-01-13 18:27:23
【问题描述】:

我正在 React 中构建一个多步骤表单,我的目标之一是在用户尚未完成填写表单时保存他们的输入。我已经使用 setItem() 将用户的输入保存在浏览器的 localStorage 中。

输入字段设置本地状态,然后将其保存到 localStorage。

但是,当页面刷新时,我想从 localStorage 检索数据并从那里设置状态变量,以便使用保存的数据预填充输入字段(如果有意义的话)

我在 componentDidMount() 中使用 setState() 来执行此操作,尽管我认为这是在创建反模式并且我不完全确定那是什么。当我使用 UNSAFE_componentWillMount 时它工作正常,但我不想使用已弃用的生命周期方法。

这是我的代码:

componentDidMount() {
    this.formData = JSON.parse(localStorage.getItem('form'));

    this.setState({
      type: this.formData.type,
      subtype: this.formData.subtype,
      brand: this.formData.brand
    })
  }

【问题讨论】:

    标签: reactjs local-storage react-lifecycle


    【解决方案1】:

    使用componentDidMount 的想法是正确的。还有另一种反模式。

    1. 不要在组件的constructor - https://reactjs.org/docs/react-component.html 之外使用this.formData = ...

    整个工作示例如下所示。我在 setState 之后添加了回调,以显示加载和保存到 localStorage 确实有效。

    
    export default class Hello extends React.Component {
      state = {
        type: undefined,
        subtype: undefined,
        brand: 0,
      }
     
      componentDidMount() {  
        const formData = JSON.parse(localStorage.getItem('form')) ?? {};
        
        if (formData) {
          formData.brand += 5
    
          this.setState({
            type: formData.type,
            subtype: formData.subtype,
            brand: formData.brand,
          }, () => {
          console.log('newState', this.state) 
          localStorage.setItem('form', JSON.stringify(this.state))
          })
        } 
    
      }
      
      render() {
        return <h1>Hello {this.state.brand} </h1>
      }
    }
    

    【讨论】:

    • 我应该提到我在 setState 之后在回调中记录了状态并且它在那里工作,但是如果我尝试在 setState 之外记录它,那么它是空的。您的代码也可以完美运行,但不会显示在组件的属性值上,例如&lt;Select options={filteredOptions} defaultInputValue={this.state.subtype} placeholder="Choose style..." onChange={this.handleChange} /&gt;
    • defaultInputValue - 似乎它可能不会对第一次渲染后的更改做出反应。 componentDidMount 在第一次渲染之后运行,所以可能有问题。对此的解决方案可能是在构造函数中初始化状态或使用布尔标志等待在componentDidMount 之后呈现Select 组件。
    【解决方案2】:

    如果您不想在componentDidMount()中检索本地存储数据,可以使用constructor函数

    constructor(){
      const formData = JSON.parse(localStorage.getItem('form'));
      const { type, subtype, brand } = formdata; 
      this.setState({ type, subtype, brand });
    }
    

    虽然我建议使用 didMount。

    componentDidMount() {
      const formData = JSON.parse(localStorage.getItem('form'));
      const { type, subtype, brand } = formdata; 
      this.setState({ type, subtype, brand });
    }
    

    【讨论】:

      猜你喜欢
      • 2018-04-03
      • 2019-06-17
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 2016-09-27
      • 2019-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多