首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >React技巧之移除状态对象中的键

React技巧之移除状态对象中的键

作者头像
chuckQu
发布2022-08-19 15:55:26
发布2022-08-19 15:55:26
2.7K0
举报
文章被收录于专栏:前端F2E前端F2E

原文链接:https://bobbyhadz.com/blog/react-remove-key-from-state-object

作者:Borislav Hadzhiev

正文从这开始~

总览

在React中,移除state对象中的键:

  1. 使用useState钩子存储state对象。
  2. 解构对象中需要移除的键,以及其他的属性。
  3. 将state设置为其他属性。

解构

代码语言:javascript
复制
import {useState} from 'react';

export default function App() {
  const initialState = {
    id: 1,
    name: 'Alice',
    salary: 100,
    department: 'development',
  };
  const [employee, setEmployee] = useState(initialState);

  const removeKey = () => {
    setEmployee(current => {
      // 👇️ remove salary key from object
      const {salary, ...rest} = current;

      return rest;
    });
  };

  return (
    <div>
      <button onClick={removeKey}>Click</button>

      <h4>{JSON.stringify(employee, null, 4)}</h4>

      <hr />

      <h2>name: {employee.name}</h2>
      <h2>department: {employee.department}</h2>
      <h2>salary: {employee.salary}</h2>
    </div>
  );
}

remove-key-from-state-object.gif

为了移除state对象中的键,我们解构了指定的键以及其余参数,并更新state对象为其余参数。

delete

同样的,你也可以使用delete操作符。

代码语言:javascript
复制
import {useState} from 'react';

export default function App() {
  const initialState = {
    id: 1,
    name: 'Alice',
    salary: 100,
    department: 'development',
  };
  const [employee, setEmployee] = useState(initialState);

  const removeKey = () => {
    setEmployee(current => {
      // 👇️ create copy of state object
      const copy = {...current};

      // 👇️ remove salary key from object
      delete copy['salary'];

      return copy;
    });
  };

  return (
    <div>
      <button onClick={removeKey}>Click</button>

      <h4>{JSON.stringify(employee, null, 4)}</h4>

      <hr />

      <h2>name: {employee.name}</h2>
      <h2>department: {employee.department}</h2>
      <h2>salary: {employee.salary}</h2>
    </div>
  );
}

如果你决定使用delete操作符,请确保使用扩展语法()创建一份state对象的副本。我们使用扩展语法来解包对象的键值对到新的对象中,并创建了浅复制。

我们永远不应该在React中改变state对象或数组。

我们将函数传递到setState ,因为函数保证以当前(最新的)状态调用。

代码语言:javascript
复制
const removeKey = () => {
  setEmployee(current => {
    // 👇️ create copy of state object
    const copy = {...current};

    // 👇️ remove salary key from object
    delete copy['salary'];

    return copy;
  });
};

当使用前一个状态计算下一个状态时,传递一个函数给setState。否则,如果我们所访问的state对象不代表最新的值,我们可能会得到一些奇怪的Race Condition。

总结

可以通过解构或者delete操作符来删除state对象中指定的键,同时需要在setState中传入函数,保证以最新的状态调用。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-06-17,如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • 总览
  • 解构
  • delete
  • 总结
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档