一些不常见的方法
lodash库
- _.chunk([‘a’, ‘b’, ‘c’, ‘d’], 2) => [[‘a’, ‘b’], [‘c’, ‘d’]]
1 2 3 4 5 6 7 8 9
| _.fill(array, 'a'); console.log(array);
_.fill(Array(3), 2);
_.fill([4, 6, 8, 10], '*', 1, 3);
|
- 深克隆 _.deepClone(obj)
- .max/.min/_.sum(数组方法)
- _. debounce
1
| const onFinish = debounce(fn, 300);
|
??运算符
??和||很像,先说一下||的功能,a || b 和 a ? a : b等价a为真则返回a,否则返回b,但是如果想实现const n = false||'default,n就只能为default,想让n可以为false就可以用??操作符,false??'default
1 2
| a ?? b a !== undefined && a !== null ? a : b
|
因为这两个表达式是等价的。
双问号(??)的提出是为了补充可选链(?),来看看这两兄弟结合使用的场景(第A行):
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
| const persons = [ { surname: 'Zoe', address: { street: { name: 'Sesame Street', number: '123', }, }, }, { surname: 'Mariner', }, { surname: 'Carmen', address: { }, }, ];
const streetNames = persons.map( p => p.address?.street?.name ?? '(no name)'); assert.deepEqual( streetNames, ['Sesame Street', '(no name)', '(no name)'] );
|
总结:a||b只要a假就取b,a??b只有a为null或undefined取b。
useHistory\useLocation
1 2 3 4 5 6 7
| import { useHistory, useLocation } from 'react-router-dom'; const location = useLocation(); const history = useHistory(); history.replace(path); history.push(path); history.goBack(path); location.pathname
|
StrictMode
1 2 3 4 5 6
| <React.StrictMode> <div> <ComponentOne /> <ComponentTwo /> </div> </React.StrictMode>
|
react.lazy
1 2 3 4 5 6 7 8 9 10 11 12 13
| import React, { Suspense } from 'react';
const OtherComponent = React.lazy(() => import('./OtherComponent'));
function MyComponent() { return ( <div> <Suspense fallback={<div>Loading...</div>}> <OtherComponent /> </Suspense> </div> ); }
|
动态引入组件,懒加载,需要的时候才加载。fallback中是加载时显示的内容。
use-query-params
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| import { useQueryParams, StringParam, withDefault, NumberParam, } from 'use-query-params'; const [query, setQuery] = useQueryParams({ name: StringParam, age: NumberParam, description: StringParam, status: withDefault(NumberParam, 1), current: withDefault(NumberParam, 1), pageSize: withDefault(NumberParam, 10), _t: NumberParam, }); setQuery({ name: undefined, age: undefined, description: undefined, status: 0, current: 1, pageSize: query.pageSize, _t: Date.now(), });
|