首页 > 解决方案 > 如何编辑本地存储值反应?

问题描述

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

Github 项目

我的想法:

我在这个论坛上问过如何删除本地存储值并得到这个答案而没有解释:堆栈溢出问题

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>
    )
  }
}

标签: javascriptreactjslocal-storage

解决方案


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

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
}

推荐阅读