React

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > React > React localStorage删除笔记

React如何使用localStorage及实现删除笔记操作过程

作者:练习两年半的工程师

这篇文章主要介绍了React如何使用localStorage及实现删除笔记操作过程,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧

1. 初始化notes

以下这段代码完成了这些操作:

const [notes, setNotes] = React.useState(
    JSON.parse(localStorage.getItem("notes")) || []
  )

useState钩子

useState 是 React 的一个钩子,用于在函数组件中引入状态。
它返回一个数组,有两个元素:

localStorage

JSON.parse

如果存储的数据是一个 JSON 字符串,例如:“[1, 2, 3]”,调用 JSON.parse 后会得到 [1, 2, 3]。

|| 运算符

2. 每次notes发生改变时,将notes保存到localStorage

  React.useEffect(() => {
    localStorage.setItem("notes", JSON.stringify(notes))
  }, [notes])

useEffect 是 React 的一个钩子,用于在函数组件中处理副作用。

它的语法如下:

React.useEffect(effectFunction, dependencies);

effectFunction 是一个函数,在特定条件下运行。
dependencies 是一个数组,控制 effectFunction 的运行时机。

localStorage.setItem 是浏览器提供的 API,用于向 localStorage 中存储键值对。
它接受两个参数:

JSON.stringify(notes)

当组件渲染后并且 notes 发生变化时:

如果 notes 没有变化:

3. 什么是 Lazy State Initialization?

通常情况下,useState 的初始值是直接计算出来的:

const [state, setState] = React.useState(computeInitialState());

为了解决这个问题,React 提供了一种惰性初始化的方法:通过向 useState 传递一个函数,而不是直接传递计算结果。这种函数只会在组件第一次渲染时执行,之后不会再次调用。

惰性初始化

const [state, setState] = React.useState(() => computeInitialState());

4. 在React中实现删除笔记的操作

<button 
    className="delete-btn"
    onClick={(event) => props.deleteNote(event, note.id)}
>
    <i className="gg-trash trash-icon"></i>
</button>

<button> 元素

回调函数中的 (event) => props.deleteNote(event, note.id) 是一个箭头函数,执行时调用 props.deleteNote 方法,并将两个参数传递给它:

<i> 是 HTML 的行内元素,通常用作图标的占位符。

  function deleteNote(event, noteId){
    event.stopPropagation()
    setNotes(oldNotes => oldNotes.filter(note => note.id !== noteId))
  }

event.stopPropagation()
作用:

场景举例:
假设笔记项的外层组件有一个点击事件绑定:

<div onClick={() => console.log("Note clicked!")}>
    <button onClick={(event) => deleteNote(event, noteId)}>Delete</button>
</div>

如果没有 event.stopPropagation()

有了 event.stopPropagation()

箭头函数 oldNotes => oldNotes.filter(...)
setNotes 接收一个更新函数,该函数的参数是当前的状态值 oldNotes
filter 方法:

完整逻辑
通过 filter 遍历 oldNotes 数组:

返回的新数组赋值给 notes,并触发组件重新渲染。

5. 删除按钮的CSS实现

.delete-btn {
  display: none;
  background: none;
  border: none;
}

作用

属性解释

隐藏元素,按钮不占据布局空间,不可见。

移除按钮的默认背景样式。

移除按钮的默认边框。

.title:hover > .delete-btn {
  display: block;
}

作用

属性解释
display: block;

让 .delete-btn 可见,并以块级元素形式显示。

> .delete-btn

实现逻辑

通过伪类 :hover,动态切换按钮的显示状态,提供更好的用户交互体验。

.trash-icon {
  cursor: pointer;
}

作用

属性解释
cursor: pointer;

鼠标悬停时显示手型指针,表示该元素可点击。

.gg-trash {
  box-sizing: border-box;
  position: relative;
  display: block;
  transform: scale(var(--ggs,1));
  width: 10px;
  height: 12px;
  border: 2px solid transparent;
  box-shadow:
      0 0 0 2px,
      inset -2px 0 0,
      inset 2px 0 0;
  border-bottom-left-radius: 1px;
  border-bottom-right-radius: 1px;
  margin-top: 4px;
}

作用

属性解释
box-sizing: border-box;

position: relative;

transform: scale(var(--ggs,1));

width: 10px; height: 12px;

border: 2px solid transparent;

设置透明的边框。

box-shadow
为垃圾桶形状添加外边框和内部边框:

border-bottom-left-radiusborder-bottom-right-radius

margin-top: 4px;

在顶部增加间距。

.gg-trash::after {
  background: currentColor;
  border-radius: 3px;
  width: 16px;
  height: 2px;
  top: -4px;
  left: -5px;
}

作用

属性解释
background: currentColor;

使用当前文本颜色作为背景颜色。

border-radius: 3px;

添加圆角,使盖子边缘更平滑。

width: 16px; height: 2px;

定义横梁的大小。

top: -4px; left: -5px;

使用绝对定位将横梁放置在垃圾桶顶部的位置。

.gg-trash::before {
  width: 10px;
  height: 4px;
  border: 2px solid;
  border-bottom: transparent;
  border-top-left-radius: 2px;
  border-top-right-radius: 2px;
  top: -7px;
  left: -2px;
}

作用

属性解释
width: 10px; height: 4px;:

border: 2px solid;:

设置盖子的边框。

border-bottom: transparent;:

移除盖子底部的边框,使其开口朝下。

border-top-left-radius 和 border-top-right-radius:

设置盖子顶部的两个角为圆角。

top: -7px; left: -2px;:

使用绝对定位将盖子放置在垃圾桶顶部。

总结:垃圾桶图标的整体实现

结合这些样式,实现了一个完整的垃圾桶图标。

交互效果总结

6. 查找当前笔记id

const [currentNoteId, setCurrentNoteId] = React.useState(
    (notes[0]?.id) || ""
  )
const currentNote = notes.find(note => note.id === currentNoteId) || notes[0]

React.useState

定义一个状态变量 currentNoteId 和其对应的更新函数 setCurrentNoteId

notes[0]?.id

|| ""
如果 notes[0]?.idundefinedcurrentNoteId 的初始值设置为空字符串 ""

效果

如果 notes 数组非空,currentNoteId 的初始值是第一项笔记的 id。如果 notes 数组为空,currentNoteId 的初始值是 “”。

notes.find(note => note.id === currentNoteId)

|| notes[0]
如果没有找到匹配的笔记(即 find 返回 undefined),使用 || 提供默认值,返回 notes[0](数组的第一项)。

到此这篇关于React自学:如何使用localStorage,以及如何实现删除笔记操作的文章就介绍到这了,更多相关React localStorage删除笔记内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文