fi3ework / blog

📝

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Knowledge fragment

fi3ework opened this issue · comments

commented
  1. React 订阅了 Context.Provieder 的 Consumer 会忽略 shouldComponentUpdate 这个生命周期直接强制更新(类似 forceUpdate),官方文档:

All consumers that are descendants of a Provider will re-render whenever the Provider’s value prop changes. The propagation from Provider to its descendant consumers is not subject to the shouldComponentUpdate method, so the consumer is updated even when an ancestor component bails out of the update.

所以如果需要通过 shouldComponentUpdate 进行性能优化的话,需要再在需要性能优化的组件外套一层 HOC,HOC 可以跟随 context.Provider 的更新并传递 props 给组件。

  1. react-router 的 Route 组件的 component 这个 props 使用的是 React.createElement 来创建 react element,所以如果传递的是内联函数,如下
const SomeCom = () => <br />
<Route path="/some-path" component={()=> <SomeCom />} />

在调用 React.createElement 时机会变成(如下为 babel 转义的 JSX)

_react.default.createElement(function () {
  return SomeCom;
});

可以看到 createElement 的第一个参数 type 是一个「临时生成」的函数,所以会导致在每次 render 的时候这个 type 都会对应不同的函数,所以 Route 在每次 render 时就会 unmount 再 mount 一次组件,导致性能问题。
解决办法是使用 Route 的 render 这个 props,render 会直接调用传递的函数作为 element。

  1. react-router 的 path 其实支持很多正则的表达式,底层使用的是 path-to-regexp 这个库,比如:
  • /:foo/:bar? 来匹配可选字符
  • /:foo* 来匹配零个存在字符
  • /:foo+ 来匹配一个或多个字符
  • /:foo(\\d+) 来匹配纯数字字符
  1. React + TS 的类型推导似乎在某些边缘 case 下有问题,比如加入了自定义守卫类型之后,无法检测出 return undefined 会导致返回的类型不匹配
    image

  2. componetWillUnmount 是异步的,比如给组件换个 key 强行 re-mount 这种操作,可能老组件的 componentWillUnmount 是发生在新组件的 constructor 之前的,容易产生竞态的问题。
    facebook/react#11106