如何编辑本地存储值?

时间:2019-02-21 18:43:47

标签: javascript reactjs local-storage

我有两个组件Display.jsx和DisplayList.jsx。组件协同工作以显示本地存储中的值。问题在于DisplayList.JSX handleEdit()方法切片。

Github project

我的想法:

我在这个论坛上问如何删除本地存储值,但得到的答案没有解释:stack overflow question

data = [
   ...data.slice(0, index),
   ...data.slice(index + 1)
 ];

它可以工作,但是现在我需要做类似的切片,以编辑旧存储值并将其替换为新存储值。但是我不知道该怎么做。

总结:在DisplayList.jsx中,方法handleEdit()需要从本地存储中获取值,并用this.state电子邮件和this.state密码值覆盖。如果有人可以解释此过程,则可奖励。

Display.jsx

import React, { Component } from 'react'
import {DisplayList} from './DisplayList';


class Display extends Component {
  constructor(props){
    let data = JSON.parse(localStorage.getItem('data'));
    super(props)
    this.state = {
      data: data,
  }

  // Methods
  this.displayValues = this.displayValues.bind(this);
  }

  displayValues(){

   return this.state.data.map((data1, index) =>
    <DisplayList
      key = {index}
      email = {data1.email}
      password = {data1.password}
      updateList = {this.updateList}
       /> 
    )

  }
  // This is the method that will be called from the child component.
  updateList = (data) => {
    this.setState({
      data
    });
  }
  render() {
    return (
      <ul className="list-group">
        {this.displayValues()}
      </ul>
    )
  }
}

export default Display;

DisplayList.jsx

import React, { Component } from 'react'
import {Button, Modal, Form} from 'react-bootstrap';


export class DisplayList extends Component {

    constructor(props){
        super(props)
        this.state = {
            email: '',
            password: '',
            show: false,
        };

        // Methods
        this.handleDelete = this.handleDelete.bind(this);
        this.onChange = this.onChange.bind(this);
        // Edit Modal
        this.handleShow = this.handleShow.bind(this);
        this.handleClose = this.handleClose.bind(this);
        this.handleEdit = this.handleEdit.bind(this);
    }

    onChange(event){
        this.setState({
            [event.target.name]: event.target.value
        })
    };
    handleClose(){
        this.setState({show: false});
    }
    handleShow(){
        this.setState({show: true});
    }
    handleEdit(event){
        event.preventDefault();
        this.setState({show: false});
        let data = JSON.parse(localStorage.getItem('data'));

        for (let index = 0; index < data.length; index++) {
          if( this.props.email === data[index].email &&
              this.props.password === data[index].password){
        }
      }
          localStorage.setItem('data', JSON.stringify(data));
          this.props.updateList(data);
    }
    handleDelete(){
        let data = JSON.parse(localStorage.getItem('data'));
        for (let index = 0; index < data.length; index++) {
            if(this.props.email === data[index].email &&
                this.props.password === data[index].password){

                data = [
                  ...data.slice(0, index),
                  ...data.slice(index + 1)
                ];

            }
        }
        localStorage.setItem('data', JSON.stringify(data));
        this.props.updateList(data);
    }


  render() {
    return (
    <div className = "mt-4">
        <li className="list-group-item text-justify">
            Email: {this.props.email} 
            <br /> 
            Password: {this.props.password}
            <br /> 
            <Button onClick = {this.handleShow} variant = "info mr-4 mt-1">Edit</Button>
            <Button onClick = {this.handleDelete} variant = "danger mt-1">Delete</Button>
        </li>
        <Modal show={this.state.show} onHide={this.handleClose}>
          <Modal.Header closeButton>
            <Modal.Title>Edit Form</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <Form>
                <Form.Group controlId="formBasicEmail">
                <Form.Label>Email address</Form.Label>
                <Form.Control 
                autoComplete="email" required
                name = "email"
                type="email" 
                placeholder="Enter email"
                value = {this.state.email}
                onChange = {event => this.onChange(event)}
                />
                </Form.Group>
                <Form.Group controlId="formBasicPassword">
                <Form.Label>Password</Form.Label>
                <Form.Control 
                autoComplete="email" required
                name = "password"
                type="password" 
                placeholder="Password"
                value = {this.state.password}
                onChange = {event => this.onChange(event)}
                />
                </Form.Group>
          </Form>
          </Modal.Body>
          <Modal.Footer>
            <Button variant="secondary" onClick={this.handleClose}>
              Close
            </Button>
            <Button variant="primary" onClick={this.handleEdit}>
              Save Changes
            </Button>
          </Modal.Footer>
        </Modal>
    </div>
    )
  }
}

1 个答案:

答案 0 :(得分:1)

在localStorage中编辑数据时,首先从localStorage获取值,如果存在则搜索值的索引,然后在该索引处更新值。

您可以通过多种方式执行此操作,但是我发现在列表上进行映射是实现此目的的最简单方法

handleEdit(event){
    event.preventDefault();
    this.setState({show: false});
    let data = JSON.parse(localStorage.getItem('data'));

    data = data.map((value) => {
         // check if this is the value to be edited
         if (value.email === this.props.email && value.password = this.props.password) {
              // return the updated value 
              return {
                   ...value,
                   email: this.state.email,
                   password: this.state.password
              }
         }
         // otherwise return the original value without editing
         return value;
    })
    localStorage.setItem('data', JSON.stringify(data));
    this.props.updateList(data);
}

要了解以上代码,您需要了解...的作用。在主旨中,它称为Spread syntax,它允许将可迭代的内容(例如数组表达式或字符串)扩展到期望零个或多个参数(用于函数调用)或元素(用于数组文字)的位置,或对象表达式将扩展到预期零个或多个键值对(用于对象文字)的位置。您也可以阅读这篇文章,以了解更多信息

What does three dots do in ReactJS

现在要检查代码

{
    ...value, // spread the original value object 
    email: this.state.email, // override email value from value object with state.email
    password: this.state.password // override password value from value object with state.password
}