美文网首页
写法技巧

写法技巧

作者: Shiki_思清 | 来源:发表于2020-12-16 10:58 被阅读0次
  1. 在if中判断数组长度不为零的正确姿势
// good
if (arr.length) {
    // todo
}
  1. 为零
// good
if (!arr.length) {
    // todo
}
  1. 判断数组是否包含某一项
// good
let arr = [1, 2, 3, 4]
if (arr.includes(a)) {
    // todo
}
  1. 解构数组进行变量值的替换
// good
let a = 1,
    b = 2
[b, a] = [a, b]
  1. 解构时重命名简化命名
// best
setForm ({aaa_bbb_ccc_ddd: one, eee_fff_ggg: two}) {
    this.one = one
    this.two = two
}
  1. 函数参数校验
// good
let checkoutType = () => {
    throw new Error('参数不能为空')
}
let findStudentByAge = (arr, age = checkoutType()) =>
    arr.filter(num => num === age)

  1. props 传递
<Grid
  data={gridData}
  pagination={false}
  autoSize={true}
  enableSort={true}
  sortOrder="desc"
  disableSelection={true}
  infiniteScroll={true}
/>
// --->
onst options = {
  pagination: false,
  autoSize: true,
  enableSort: true,
  sortOrder: 'desc',
  disableSelection: true,
  infiniteScroll: true,
}

<Grid
  data={gridData}
  options={options}
/>

  1. useState 过多
function AutocompleteInput() {
  const [isOpen, setIsOpen] = useState(false)
  const [inputValue, setInputValue] = useState('')
  const [items, setItems] = useState([])
  const [selectedItem, setSelectedItem] = useState(null)
  const [activeIndex, setActiveIndex] = useState(-1)

  const reset = () => {
    setIsOpen(false)
    setInputValue('')
    setItems([])
    setSelectedItem(null)
    setActiveIndex(-1)
  }

  const selectItem = (item) => {
    setIsOpen(false)
    setInputValue(item.name)
    setSelectedItem(item)
  }

  ...
}

替换成:

const initialState = {
  isOpen: false,
  inputValue: "",
  items: [],
  selectedItem: null,
  activeIndex: -1
}
function reducer(state, action) {
  switch (action.type) {
    case "reset":
      return {
        ...initialState
      }
    case "selectItem":
      return {
        ...state,
        isOpen: false,
        inputValue: action.payload.name,
        selectedItem: action.payload
      }
    default:
      throw Error()
  }
}

function AutocompleteInput() {
  const [state, dispatch] = useReducer(reducer, initialState)

  const reset = () => {
    dispatch({ type: 'reset' })
  }

  const selectItem = (item) => {
    dispatch({ type: 'selectItem', payload: item })
  }

  ...
}

  1. 单一职责useEffect
  useEffect(() => {
    fetch(`/posts/${id}`).then(/* do something */)

    setVisibility(unlisted)
  }, [id, unlisted])

换成

  useEffect(() => { // when id changes fetch the post
    fetch(`/posts/${id}`).then(/* ... */)
  }, [id])

  useEffect(() => { // when unlisted changes update visibility
    setVisibility(unlisted)
  }, [unlisted])
  1. state 的多个状态
function Component() {
  const [isLoading, setIsLoading] = useState(false)
  const [isFinished, setIsFinished] = useState(false)
  const [hasError, setHasError] = useState(false)

  const fetchSomething = () => {
    setIsLoading(true)

    fetch(url)
      .then(() => {
        setIsLoading(false)
        setIsFinished(true)
      })
      .catch(() => {
        setHasError(true)
      })
  }

  if (isLoading) return <Loader />
  if (hasError) return <Error />
  if (isFinished) return <Success />

  return <button onClick={fetchSomething} />
}

替换成:

function Component() {
  const [state, setState] = useState('idle')

  const fetchSomething = () => {
    setState('loading')

    fetch(url)
      .then(() => {
        setState('finished')
      })
      .catch(() => {
        setState('error')
      })
  }

  if (state === 'loading') return <Loader />
  if (state === 'error') return <Error />
  if (state === 'finished') return <Success />

  return <button onClick={fetchSomething} />
}

替换成Typescript

const [state, setState] = useState<'idle' | 'loading' | 'error' | 'finished'>('idle')

相关文章

  • 写法技巧

    在if中判断数组长度不为零的正确姿势 为零 判断数组是否包含某一项 解构数组进行变量值的替换 解构时重命名简化命名...

  • 简洁的Bash Programming技巧(二)

    简洁的Bash Programming技巧(二) 1. 检查命令执行是否成功 第一种写法,比较常见: 简洁的写法:...

  • 【基础系列】JS使用技巧专题

    JS使用技巧专题 1开发技巧 1.1函数使用 1.1.1函数声明方式 JS函数的写法总结 http://blog....

  • 新媒体笔记:形式与内容并重才是完美呈现

    本周勾老师分别从形式和内容两个方面讲了五个知识点:配图技巧、内部链接、故事写法、鸡汤写法以及干货写法。 一、配图技...

  • python小技巧

    能调用方法的一定是对象。 技巧#1 字符串翻转 技巧#2 矩阵转置 矩阵转置 自己喜欢的一种写法: 技巧#3 a ...

  • 隶书部首写法技巧

    隶书是汉代书法发展史上的高峰,《乙瑛碑》是汉隶最兴盛时期的代表性作品,其用笔沉着厚重,结字端庄雍容,具有宗庙之美,...

  • 小白新手开发网站-记录-2.表单提交

    前言:我也不清楚最简单的写法 我得意识中只有这种写法 使用的技巧:..form表单 id 类选择器 inpu...

  • 读《实用文教学教什么》(四十七)

    关于学习表达技巧我们要明确:1.技巧不仅仅是写法,它不能被简单地还原为章法、句法。技巧有它自己的位置,它的正...

  • 移步换形描写法

    移步换形描写法是描写技巧之一。与动点描写法相近。不同的是,动点描写法是变化角度去写同一对象,而移步换形法是变化角度...

  • 萌薇手账课作业二:版式/标题字/卡通形象

    补课中...... 萌薇老师手账课第4-8节课,主要介绍配色及排版技巧、标题字写法、简笔画技巧。 满满的干货,很多...

网友评论

      本文标题:写法技巧

      本文链接:https://www.haomeiwen.com/subject/katwiktx.html