14 js代码编写相关

56 阅读1分钟

React 列表渲染

不要使用list.length && list.map.....
页面会显示0
1. 可以用 !!list.length && list.map..... 会转为boolean
2. list.length >0 && list.map...
3. list.length ? <Component list={list} /> : null;

Map 简单实用

// 先实例出来再添加属性
  const map = new Map();
  map.set(1, "01").set(2, "02").set(3, "03");
  console.log(map.get(1));
  // 直接实例化并添加属性
  const map2 = new Map([
    ["get", () => console.log("获取")],
    ["set", () => console.log("设置")],
  ]);
  map2.get("set")!();
// 对象形式写 Map映射
const list = [];
  list.forEach((item) => {
    if (item.title === "未使用") {
      item.title = "0";
    } else if (item.title === "已使用") {
      item.title = "1";
    }

    if (item.status === "待反馈") {
      item.status = "0";
    } else if (item.status === "已反馈") {
      item.status = "1";
    }
  });

  const usedObj = {
    未使用: "0",
    已使用: "1",
  };
  const feedbackObj = {
    待反馈: "0",
    已反馈: "1",
  };
  const item = { title: "未使用", status: "已反馈" };
  // 0, 1
  console.log(usedObj[item.title], feedbackObj[item.status]);

用findIndex+splice 替换 forEach + splice

arr.forEach((item, index){
    if(item.id === id){
        arr.splice(index, 1)
    }
})
// 换成这种
arr.splice(arr.findIndex((item, index)=> item.id === id),1)
// 这个场景就 通过 `findIndex` 直接找到索引, 删除那一项 这样不会像 修改之前那样 每次都要遍历完数组 复杂度会大大降低

将判断提前

if(条件为真){
...
...
...
}
换成
if(!条件为真) return
...
...
...
将判断提前,就不用if里面包裹大量逻辑,并且优化性能,当 dataNum 不存在的时候 就不会执行下面的代码了

避免使用含义不清的数字

const width = (x.width + y.width) * 120
改成
const unitWidth = 120
const width = (x.width + y.width) * unitWidth