1、组件
React.Component
React.PurComponent
React.PurComponent
实现shouldComponentUpdate(),进行diff算法浅比较
使用场景 组件被赋予相同的props和state,render()函数渲染相同的内容
深度数据结构变化使用forceUpdate(), immutable
2、装换元素-操作元素API
React.cloneElement()
//验证是否为React元素,返回布尔值
React.isValidElement()
//用于处理this.props.children
React.Children
//子节点null返回null其他类似,Fragment 对象为一个节点
React.Children.map()
React.Children.forEach
React.Children.count
//不接受map返回值(数组),only要React元素
React.Children.only
//复杂数据,以数组扁平展开,可在渲染函数之前操作子节点eg,排序获取子集(看起来有点用)
React.Children.toArray
!React.cloneElement()返回元素的 props 是将新的 props 与原始元素的 props 浅层合并后的结果。新的子元素将取代现有的子元素,而来自原始元素的 key 和 ref 将被保留。
3、Fragments--减少不必要嵌套
React.Fragment
4、Refs
//操作元素
React.createRef
可向下转发
React.forwardRef
//例子下面
5、Suspense--等待操作完进行渲染
用于React.lazy动态加载组件
React.lazy
React.Suspense
React.lazy
- 允许你定义一个动态加载的组件。
- 这有助于缩减 bundle 的体积,并延迟加载在初次渲染时未用到的组件。
-----使用配合Suspense
------可放深处,最佳放你想展示加载指示器(loading indicator)的位置
// 这个组件是动态加载的
const SomeComponent = React.lazy(() => import('./SomeComponent'));
// 该组件是动态加载的
const OtherComponent = React.lazy(() => import('./OtherComponent'));
function MyComponent() {
return (
// 显示 <Spinner> 组件直至 OtherComponent 加载完成
<React.Suspense fallback={<Spinner />}>
<div>
<OtherComponent />
</div>
</React.Suspense>
);
}
6、hook
基础 Hook
* useState
* useEffect
* useContext
额外的 Hook
* useReducer
* useCallback
* useMemo
* useRef
* useImperativeHandle
* useLayoutEffect
* useDebugValue
7、React.memo()
记忆,相同结果,直接使用上一次结果,跳过渲染组件的操作
仅检查props,有hook,仍会渲染;只进行复杂对象浅比较,控制对比用比较函数
React.meno(MyComponent,funtion(prevProps,nextProps){})
8、React.createELement()
0、例子
//ref
class MyComponent extends React.Component {
constructor(props) {
super(props);
//注册
this.inputRef = React.createRef();
}
render() {
//绑定
return <input type="text" ref={this.inputRef} />;
}
componentDidMount() {
//使用 this.inputRef.current.focus();
}
}
//forwardRef
-----转发 refs 到 DOM 组件
-----在高阶组件中转发 refs
const FancyButton = React.forwardRef((props, ref) => (
//绑定
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
// You can now get a ref directly to the DOM button:
//注册
const ref = React.createRef();
//转发
<FancyButton ref={ref}>Click me!</FancyButton>;
//记忆组件详细例子
function MyComponent(props) {
/* 使用 props 渲染 */
}
function areEqual(prevProps, nextProps) {
/*
如果把 nextProps 传入 render 方法的返回结果与
将 prevProps 传入 render 方法的返回结果一致则返回 true,
否则返回 false
*/
}
export default React.memo(MyComponent, areEqual);