javascript - 如何编辑本地存储值 react ?

标签 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 密码值覆盖。如果有人能解释这个过程,奖金。

显示.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;

显示列表.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>
    )
  }
}

最佳答案

在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 并且它允许在零个或多个参数(用于函数调用)或元素(用于数组文字)所在的位置扩展诸如数组表达式或字符串的可迭代对象expected,或者在期望零个或多个键值对(对于对象文字)的地方扩展的对象表达式。您也可以阅读这篇文章以了解更多信息

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
}

关于javascript - 如何编辑本地存储值 react ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54814129/

相关文章:

javascript - 调用 localStorage.clear() 如果用户在一段时间内没有参与应用程序

JavaScript For循环: Assignment to character not working

reactjs - a11y : What is the correct `<track>` element for video chats?

javascript - React Redux 重新选择 - 未定义状态

jquery - 在本地存储保存功能上,也将变量传递给 MySQL 数据库

javascript - React Native - JSON 本地存储

javascript - 来自 mysql 表的简单 d3.js 关系图

javascript - 为什么 JSfiddle 和 Chrome console 对同一个函数返回不同的值?

javascript - 如何解决类型错误: Cannot read property 'filter' of undefined

reactjs - React Fusion-Charts 条形宽度