【问题标题】:Problem with Edit function overrides the local storage and throws errorsEdit 函数的问题会覆盖本地存储并引发错误
【发布时间】:2021-03-24 11:51:23
【问题描述】:

当我尝试保存甚至弄乱我的删除功能时,我的编辑功能会覆盖本地存储。不知道问题出在哪里。我尝试在类似的帖子中找到解决方案,但无法弄清楚。完整代码的 GitHub 存储库:https://github.com/ottowoolf/NotesApp

import React, { useState, useEffect } from "react";
import { Form, Container, Button } from "react-bootstrap";
import { useParams } from "react-router-dom";

export const Edit = ({ notes, setNotes }) => {
  const [form, setForm] = useState({
    title: "",
    text: "",
    id: "",
  });
  const { id } = useParams();

  useEffect(() => {
    let index = notes.find((n) => n.id === id);
    let selectedNote = notes[index];
    console.log(notes[index]);
    console.log(id);
    console.log(selectedNote);
    setForm(selectedNote);
  }, [id, notes]);

  const handleChange = (e) => {
    const { value, name } = e.target;
    setForm({ ...form, [name]: value, id });
    console.log(form);
  };

  const saveNote = () => {
    if (form.title.trim() !== "" || form.text.trim() !== "") {
      setNotes((note) => {
        // return array - with the object of /id/ modified
        let index = note.find((n) => n.id === id);
        let newNotes = [...note];
        newNotes[index] = form;
        console.log(newNotes[index]);
        return newNotes[index];
      });
    }
  };

  return (
    <React.Fragment>
      <Container>
        <Form className='mt-3 w-50'>
          <Form.Group controlId='formBasicEmail'>
            <Form.Control
              onChange={handleChange}
              value={form.title}
              name='title'
              type='text'
            />
          </Form.Group>

          <Form.Group controlId='formBasicPassword'>
            <Form.Control
              onChange={handleChange}
              value={form.text}
              name='text'
              as='textarea'
              cols='30'
              rows='10'
            />
          </Form.Group>
        </Form>
        <Button onClick={saveNote} className='btn btn-success'>
          Save
        </Button>
      </Container>
    </React.Fragment>
  );
};

【问题讨论】:

  • 您的Edit 组件没有要调用的函数来设置localStorage。它如何覆盖localStorage
  • 我完全不知道@SinanYaman 我在不同的组件中获取和设置项目但是一旦我点击保存,数据就会从本地存储中删除:(
  • 不,我要指出的是这不可能发生。我浏览了您的代码,发现在 Routes.jsx 中,您设置了本地存储。问题很可能存在
  • 我会看看那个。谢谢:)

标签: javascript reactjs react-router react-hooks


【解决方案1】:

分叉您的 GitHub 存储库并使用代码和框对其进行编辑

这是链接 https://codesandbox.io/s/aged-dawn-bnv6v?file=/src/pages/Edit.js

如果有任何遗漏,请告诉我。

另外,我建议您稍微清理一下您的代码。它看起来很适合 Notes 应用程序。

【讨论】:

  • 感谢@abhishek 非常乐于助人的伙伴。肯定需要清理代码。目前仍然是菜鸟和学习重构。干杯队友
  • 没问题@Otto,解决方案有帮助吗?如果您是初学者,那真的很棒,一切顺利。
  • 是的,解决方案奏效了?再次感谢!
猜你喜欢
  • 1970-01-01
  • 2021-10-26
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 2019-10-12
  • 1970-01-01
  • 2020-07-16
  • 1970-01-01
相关资源
最近更新 更多