useState使用

例子🌰1:
userInfo 模型
✅ TypeScript 定义和使用示例:

// 定义类型
interface UserInfo {
  name: string;
}

// 示例使用
const user: UserInfo = {
  name: "张三",
};

console.log(user.name); // 输出:张三

✅ 如果你在 React 中使用 useState 管理它:

const [user, setUser] = useState<UserInfo>({ name: "" });

// 如果要修改 name 需要这么写
setUser(prev => ({
  ...prev,
  name: "李四",
}));

//改成方法 更新 name 的方法
const setUserName = (newName: string) => {
  setUser(prev => ({
    ...prev,
    name: newName,
  }));
};


使用 ...prev 是为了保留其他字段(如果以后有更多字段,比如 age、email 等)。

例子🌰2:


const [sections, setSections] = useState<Section[]>([]);
//增。增。增。增。增。增。增
// ======================
// 方法1:
// 添加后面
//setSections(prev => [
//    ...prev,
//    {
//      title,
//      data: [{ time }],
//    },
//  ]);

// 添加到前面
//setSections(prev => [
//  {
//    title: "0",
//    data: [{ time: Date.now() }],
//  },
//  ...prev, // 把原有的放到后面
//]);
⬇️
// 弄成方法
// 添加 Section 的函数
const addSection = (title: string, time: number) => {
  setSections(prev => [
    ...prev,
    {
      title,
      data: [{ time }],
    },
  ]);
};
// 封装:向前插入 section(类似 unshift)
const prependSection = (title: string, time: number) => {
  setSections(prev => [
    {
      title,
      data: [{ time }],
    },
    ...prev,
  ]);
};
//方法2:
const newSections = [...sections]; // 复制一个新数组
newSections.push({
  title: "3",
  data: [{ time: Date.now() }],
});
setSections(newSections); // ✅ 使用新引用

// 删。删。删。删。删。删。删
// ======================
//✅ 1. 根据 title 删除整个 section
// 方法
const removeSectionByTitle = (titleToRemove: string) => {
  setSections(prev =>
    prev.filter(section => section.title !== titleToRemove)
  );
};

// 示例调用
removeSectionByTitle("1");
//✅ 2. 根据某个时间戳,从 section 的 data 中删除某一项
//比如删除某个 section 里的 { time: 123456789 }:
const removeItemFromSection = (title: string, timeToRemove: number) => {
  setSections(prev =>
    prev.map(section =>
      section.title === title
        ? {
            ...section,
            data: section.data.filter(item => item.time !== timeToRemove),
          }
        : section
    ).filter(section => section.data.length > 0) // 可选:过滤掉空的 section
  );
};

// 示例调用
removeItemFromSection("1", 1715080000000);


✅ 3. 删除第一个 / 最后一个 section(基于位置)
// 删除第一个
const removeFirstSection = () => {
  setSections(prev => prev.slice(1));
};

// 删除最后一个
const removeLastSection = () => {
  setSections(prev => prev.slice(0, -1));
};








©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容