iidear / blog

blog
0 stars 0 forks source link

React-CONCEPTS #2

Open iidear opened 5 years ago

iidear commented 5 years ago

https://reactjs.org/docs/hello-world.html

iidear commented 5 years ago

JSX

Preact 的作者写过一篇文章解释 jsx,可以说很清晰了。

一般语法

const element = <h1 className="greeting">Hello, jsx!</h1>

经过 babel + plugin-transform-react-jsx 处理之后,等价于

const element = React.createElement(
  'h1',
  { className: 'greeting' },
  'Hello, jsx!'
)

代码执行之后,返回一个对象(VNode),类似于

const element = {
  type: 'h1',
  props: {
    className: 'greeting',
    children: 'Hello, jsx!'
  }
}

注意点

iidear commented 5 years ago

Rendering Elements

const element = <h1>hello, react!</h1>;
const root = document.getElementById('root');
ReactDOM.render(element, root);

element 是一个 VNode (js对象),root 是一个 DOM Node。

ReactDOM.render 方法会将 element 表示的内容更新到 DOM 中。

使用 diff 算法,只更新必要的部分,尽可能地减少 DOM 操作。

Components、Props、State、Lifecycle

组件

状态

生命周期

事件绑定

// 推荐 const btn = <button onClick={this.submit.bind(this, data)}>submit

iidear commented 4 years ago

API

https://zh-hans.reactjs.org/docs/react-api.html

概览

iidear commented 4 years ago

组件

生命周期

声明周期速查表

https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/

相关方法

备注

错误处理

处理派生 state

派生 state 即数据来自外部的 state(跟随 props 变化的 state).

处理方式:

  1. 使用受控组件
  2. 使用非受控组件,通过在组件上设置不同的 key 来重置组件。
  3. 复杂组件,如带有中间状态的 Picker 等,使用 componentDidUpdate 或 getDerivedStateFromProps。通过比较 prevProps 和当前传入 props 是否一致判断是外部更新还是组件内部更新。
iidear commented 4 years ago

组件性能优化

合理拆分组件

用好 shouldComponentUpdate

  1. 每次触发 render (setState、forceUpdate)。都会从根节点开始遍历。
  2. 从根节点开始,会跳过不需要重新 render 的组件。
  3. 需要重新 render 的组件的所有的子组件会根据 shouldComponentUpdate 决定是否重新 render .

优化方式:

https://blog.isquaredsoftware.com/2020/05/blogged-answers-a-mostly-complete-guide-to-react-rendering-behavior/

iidear commented 4 years ago

Build your own React

https://pomb.us/build-your-own-react/

iidear commented 4 years ago

TODO: 源码中的性能优化