【发布时间】: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