useMemo
useMemo
useMemo 是拿来保持一个对象引用不变的。useMemo 和 useCallback 都是 React 提供来做性能优化的。比起 classes, Hooks 给了开发者更高的灵活度和自由,但是对开发者要求也更高了,因为 Hooks 使用不恰当很容易导致性能问题。
假设有个 component,在 dataConfig 变化的时候重新去 fetchData:
1 | <Child |
如果是个 Class Component,会这么写:
1 | class Child extends React.Component<Props> { |
使用 Hooks 后长这样:
1 | const Child = ({ fetchData, dataConfig }: Props) => { |
使用 Class Component 时我们需要手动管理依赖,但是使用 Hooks 时会带来副作用:React 使用的是Object.is(),如果fetchData的 reference 变了,也会触发 useEffect。
虽然逻辑上 React 的处理是合理的,但是还是需要手动去解决它导致的性能问题:官方提供了 useCallback 这个 hooks,用于解决函数引用问题。
useRef
useRef
- mutable ref
- presist
eg: 实现一个需求:点击按钮时 input 自动聚焦。
- createRef 实现
1 | const HomePage = () => { |
- useRef 实现
1 | const HomePage = () => { |
两者的区别在于:createRef 每次渲染会返回一个新的引用,而 useRef 返回的是相同的引用(persist)。对于函数式组件,每次 useState 会造成整个组件的重新渲染,但是 uesRef 可以保证引用不变,不会触发 re-render。
Webpack配置
项目文件目录
1 | -Demo |
- src:代码开发目录
- build:开发环境 webpack 输出目录
- dist:生产环境 webpack 输出目录
- package.json:项目配置
- webpack.config.js:开发环境配置
- webpack.production.config.js:生产环境配置
webpack 配置文件
需命名为 webpack.config.js
1 | const path = require("path") // 模块 |
webpack-dev-server
- 通过 npm 安装:npm i webpack-dev-server
- 运行命令:webpack-dev-server –devtool eval –port 9876 –progress –colors – compress –hot –inline –content-base ./build
可以在 package.json 中的 script 加一个启动项。 - –devtool eval:在报错时精确到文件的行号
- –progress:显示编译的输出内容进度
- –compress:启用 gzip 压缩
- –hot:热更新,无需刷新浏览器
- –colors:显示编译的输出内容颜色
- –inline:自动刷新模式。默认为 iframe。
- –content-base:设置输出目录。
What is the Pure Function
Function
function has special rules:
- It must work for every possible input value
- And it has only one relationship for each input value
Although each input will only have one output, but for different inputs may have the same output.
Pure function
Given all these, pure functions have a big set of advantages. They are easier to read and understand, as they do one thing. There is no need to look outside the function code and check for variables. There is no need to think how changing the value of the variable will affect other functions. No mutations in other functions will affect the result of the pure function for a specific input.
Pure functions are easier to test, as all dependencies are in the function definition and they do one thing.
For Example:
1 | var arr = [1, 2, 3] |
Another Example:
1 | // Impure |