Hibop.github.io
Hibop.github.io copied to clipboard
关于React 十问之 由浅入深
1. react为什么要使用JSX,什么是JSX?
2. 什么是虚拟DOM,怎样理解虚拟DOM?
3. React是怎样渲染的,渲染机制, 初始化渲染和更新渲染?
4. Diff算法怎么理解?
5. setState之异步理解?
- this.setState({count:2}) // 常见
- 返回对象的回调: this.setState((state, props) => { })
- 异步set : this.setState({count:3}, ()=>{ // TODO sth })
- Hook: const [count, setCount] = useState(0);;;setCount(count+2)
- 监听states 变化 : componentWillReceiveProps (nextProps) {} 1.16前
6. React为什么要使用key?
7. React如何更新UI?
8.相对angular 、Vue, react有什么特点?
9. 怎样做React 性能优化?
10. React纯组件、控制组件、高阶组件理解?
11. React与Redux、immutable的结合使用?
12. React暴露的API以及安全处理?
13. 纯组件 | 类组件, 同步|异步组件, 动态组件, 高阶组件, 受控|不受控组件
- React.PureComponent 通过props和state的浅比较实现shouldComponentUpdate(),
- 高阶组件:
// 属性代理
const Component = (Wrapped) => {
return class extends React.Component {
const props = {
...this.props,
name: "这是高阶组件"
};
return <Wrapped {...props} />;
}
}
// 反向继承: super 改变改组件的 this 方向,继而就可以在该组件处理容器组件的一些值
const Seventeen = (WrappedComponent)=>{
return class extends WrappedComponent {
componentDidMount() {
this.setState({baseName:'这是通过反向继承修改后的基础组件名称'})
}
render(){
return super.render();
}
}
}
14. constructor和super, this-bind
export default class Ten extends React.Component {
constructor() { // class 的主函数
super() // React.Component.prototype.constructor.call(this),其实就是拿到父类的属性和方法
this.state = { };
this.handler = this.handler.bind(this);
}
}
// 在不使用构造函数的情况下初始化本地状态,并通过使用箭头函数声明类方法
export default class Ten extends React.Component {
state = { value: 0 }; // 不写构造函数class默认添加并super()
handler = () => {
this.setState(prevState => ({
value: prevState.value - 1
}));
}
}
15. 你可能不知道的 React Hooks
- http://www.taoweng.site/index.php/archives/296/
- https://medium.com/@sdolidze/the-iceberg-of-react-hooks-af0b588f43fb
React 是怎样炼成的:
一篇很好的框架设计过程的总结文章:https://segmentfault.com/a/1190000013365426?utm_source=tag-newest
-
php字符拼接时代 到 标签扩展时代JSX;
-
DOM重新构建(php灵感)【状态丢失,焦点、滚动等】Diff算法 ====> DOM 复用 ====> Diff(版本控制思想)【树形结构的算法复杂度O(n3)】 ====> 忽略元素的整体移动(只有拖拽很少场景),只有子元素的增删改,所以只对比子元素
====> 不同的两个元素会产生不同的树, 可以使用key属性来表明不同的渲染中哪些元素是相同的 O(n) -
vitual DOM React 其实实现了对 DOM 节点的版本控制。 DOM 是复杂的,对它的操作(尤其是查询和创建)是非常慢非常耗费资源:
- CSS 规则查找匹配的节点样式信息, 缓存样式信息;
- 再根据样式计算节点布局, 缓存定位信息 来想想 React ,其实它只在 diff 算法中用到了 DOM 节点,而且只用到了标签名称和部分属性。 如果用更轻量级的 JS 对象来代替复杂的 DOM 节点,然后把对 DOM 的 diff 操作转移到 JS 对象,就可以避免大量对 DOM 的查询操作。这种方式称为 Virtual DOM。
-
社区优化项 [] 批处理 [] 不可变数据
function createStore (reducer) {
let state = null
const listeners = []
const subscribe = (listener) => listeners.push(listener)
const getState = () => state
const dispatch = (action) => {
state = reducer(state, action)
listeners.forEach((listener) => listener())
}
dispatch({}) // 初始化 state
return { getState, dispatch, subscribe }
}