Live Note

Remain optimistic

直接使用 su 权限移除镜像的 quarantine 标志

1
sudo xattr -rd com.apple.quarantine /Applications/<application-name>

一旦声明,值不可变

1
2
const PI = 3.14
PI = 3 //TypeError: Assignment to constant variable.

只声明不赋值也会报错。

1
const foo; //SyntaxError: Missing initializer in const declaration

实质为变量指向的内存地址不可变动

const 只能保证这个指针是固定的,不能控制数据结构的变化。

1
2
3
const foo = {}
foo.prop = 123 //Success
foo = {} //TypeError: 'foo' is read-only

对象冻结方法

使用 Object.freeze 函数,冻结对象

1
const foo = Object.freeze({})

冻结属性的函数

1
2
3
4
5
6
7
8
var makeConstant = (obj) => {
Object.freeze(obj)
Object.keys(obj).forEach((key, i) => {
if (typeof obj[key] === "object") {
makeConstant(obj[key])
}
})
}

type="module"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>

<script type="module">
// will not block the button
console.log(this) // undefined
console.log(import.meta.url) // the url of import file
</script>
<script>
// will block the button
console.log(this) // window
</script>

<script async type="module" src="http://example.com/test.js">
// will run immediate when the file is load
// example.com needs the Access-Control-Allow-Origin flag
import {sayHi} from 'sayHi' // this will get error because no path import in this module block.
</script>

<script nomodule>
alert("The Browser can not support the module import.")
</script>
</head>
<body>
<button>Button</button>
</body>
</html>

parseInt 中塞 number

1
2
parseInt(0.000001) // 0
parseInt(0.0000001) // 1

为什么会得到这样的结果?

  1. parseInt(arg: string):接收的是一个string变量。
  2. 0.0000001转成string会变为1e-7
  3. parseInt('1e-7')结果为1

所以要截取小数,最好还是使用Math.trunc(n)

useRef

  • mutable ref
  • presist

eg: 实现一个需求:点击按钮时 input 自动聚焦。

  • createRef 实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const HomePage = () => {
const input = createRef<HTMLInputElement>()

const handle = () => {
if (input.current) {
input.current.focus()
}
}

return (
<div>
<input ref={input} />
<button onClick={handle}>focus</button>
</div>
)
}
  • useRef 实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const HomePage = () => {
const input = useRef<HTMLInputElement | null>(null)

const handle = () => {
if (input.current) {
input.current.focus()
}
}

return (
<div>
<input ref={input} />
<button onClick={handle}>focus</button>
</div>
)
}

两者的区别在于:createRef 每次渲染会返回一个新的引用,而 useRef 返回的是相同的引用(persist)。对于函数式组件,每次 useState 会造成整个组件的重新渲染,但是 uesRef 可以保证引用不变,不会触发 re-render。

Read more »