React To Do List,如何将另一个项目添加到localStorage键数组

时间:2019-09-21 09:25:26

标签: reactjs local-storage

我设法从addNote页面上找到了如何为localStorage中的注释键赋予一个值,但是我似乎无法解决如何使它成为一个新值,从而在注释键下创建一个新值,而不是只是重新分配便笺值。我相信有一个for循环将循环到下一个数组索引,或者if语句将解决此问题并允许添加项,但是我不确定在哪里放置它。在解决此问题方面的任何帮助将不胜感激:)

在此处下载React项目文件:docs

下面是我用来获取输入值并将其添加到文件storage.js(位于src / services / storage.js中)的注释键中的代码

class AddNote extends Component {
    constructor(props) {
        super(props)

        this.state = {
            //title: [],
            //content: []
            items: []

        }

        let note = getLocalItem(keys.note);

        if(!note) {
        note = [];
        }

        this.addNote = this.addNote.bind(this);
    }

    addNote(event) {
        console.log("Working")

        if( this.theTitle.value !== "" ) {
            var newItem = {
                title: this.theTitle.value, 
                content: this.theContent.value
            };
        }



        this.setState((prevState) => {
            return {
                items: prevState.items.concat(newItem)
            };
        });



        const form = {
            title: this.state.title,
            content: this.state.content
        }




        setLocalItem('note', this.theTitle.value + " - " + this.theContent.value);



1 个答案:

答案 0 :(得分:0)

您只是不想将下一个内容字段'note'添加到localStorage中的现有值...下面的代码读取componentDidMount上的localStorage值;然后在每次单击按钮时,更新(而不是替换)localStorage阵列...

相关的组件

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      inputs: [],
      lastInput: ''
    };
    this.click = this.click.bind(this);
  }

  componentDidMount() {
    this.getExistingArray();
  }

  getExistingArray() {
    if (localStorage.getItem('inputs')) {
      var storedInputs = localStorage.getItem('inputs');
      this.setState({ inputs: storedInputs }, function () { console.log("from localStorage We got:", this.state.inputs); });
    }
  }

  click() {
    var newInput = [...this.state.inputs, this.state.lastInput];
    localStorage.setItem('inputs', newInput);
    this.getExistingArray();
  }

  recordInput(e) {
    this.setState({ lastInput: e.target.value });
  }

  render() {
    return (
      <div>
        <input type='text' onChange={this.recordInput.bind(this)} />
        <button onClick={this.click}>Click to update the Array</button>
        <br /> Array: {this.state.inputs}
      </div>
    );
  }
}

完成working stackblitz

更新:根据提问者的评论更新了以下功能

  click() {
    var newInput = [...this.state.inputs, this.state.lastInput];
    localStorage.setItem('inputs', newInput);
    this.getExistingArray();

    var newInputTag = 'inputs' + this.state.inputs.length;
    localStorage.setItem(newInputTag, this.state.lastInput);
  }

UPDATE2 : 检索并打印在页面上的所有本地存储对象

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      inputs: [],
      lastInput: '',
      localStoragePairs: []
    };
    this.click = this.click.bind(this);
  }

  componentDidMount() {
    this.getExistingArray();
  }

  getExistingArray() {

    for (var i = 0; i < localStorage.length; i++) {

      var key = localStorage.key(i);
      var value = localStorage.getItem(key);

      var updatedLocalStoragePairs = this.state.localStoragePairs;
      updatedLocalStoragePairs.push({ 'keyName': key, 'valueName': value });

      this.setState({ localStoragePairs: updatedLocalStoragePairs });
    }
    console.log("complete localStoragePairs:", this.state.localStoragePairs);

    if (localStorage.getItem('inputs')) {
      var storedInputs = localStorage.getItem('inputs');
      this.setState({ inputs: storedInputs }, function () { console.log("from localStorage We got:", this.state.inputs); });
    }
  }

  click() {
    var newInput = [...this.state.inputs, this.state.lastInput];
    localStorage.setItem('inputs', newInput);
    this.getExistingArray();

    var newInputTag = 'inputs' + this.state.inputs.length;
    localStorage.setItem(newInputTag, this.state.lastInput);
  }

  recordInput(e) {
    this.setState({ lastInput: e.target.value });
  }

  render() {
    var LocalSotrageContent = this.state.localStoragePairs.map((value, index) => {
      return <tr key={index}> <td>{value.keyName}</td>  <td>{value.valueName}</td> </tr>
    });


    return (
      <div>
        <input type='text' onChange={this.recordInput.bind(this)} />
        <button onClick={this.click}>Click to update the Array</button>
        <table>
          <thead>
            <tr>
              <th>All Local Storage objects by Name</th>
              <th>All Local Storage objects by Value</th>
            </tr>
          </thead>
          <tbody>
            {LocalSotrageContent}
          </tbody>
        </table>
        <br />
      </div>
    );
  }
}