react库的那些重要的Change

React@15.x

1. React的生命周期

Mounting:

  • constructor
  • componentWillMount
  • componentDidMount
  • render

Updating

  • componentWillReceivedProps
  • SCU
    • shadow state and props comparision
  • componentWillUpdate
  • render
  • componentDidUpdate

Unmounting

  • componnentWillUnmount

2. Error handling

js内部的error会导致程序崩溃,会在页面上渲染出晦涩的错误提示,React没有提供方式可以恢复现场。

// react@15.6.2
class App extends React.Component {
  componentWillMount() {
     throw new Error('something Wrong')
  }
  render() {
    return <div>
      App render
    </div>
  }
}
ReactDom.render(<App />, document.querySelector('#root')) // 直接白屏
复制代码

React@16.0

  • Components can now return arrays and strings from render
  • ErrorBoundary
    • componengDidCatch
    • getDerivedStateFromError
  • ReactDOM.createPortal()

ErrorBoundary

  • 能捕获

    • constructor内的错误
    • 生命周期内的错误
    • render过程的错误
  • 不能捕获

    • event handler,可以在代码里用try{}catch(e){}
    • 异步代码
    • 服务端渲染
    • ErrorBoudary内部的代码
// 添加 ErrorBoundary 组件
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  componentDidCatch(error, info) {
    this.setState({ hasError: true });
  }
  render() {
    if (this.state.hasError) {      
      return <h1>Something went wrong.</h1>; // falllback ui
    }
    return this.props.children;
  }
}
const el = <ErrorBoundary>
  <App />
</ErrorBoundary>
// 页面会显示Something went wrong.的文本内容
ReactDom.render(el, document.querySelector('#root')) 
复制代码

React@16.3

1. 生命周期

  • Mounting
    • componentWillMount之前增加 static getDerivedStateFromProps
    • componentWillMount/UNSAFE_ComponentWillMount
  • Updating
    • SCU的之前增加static getDerivedStateFromProps
    • componentWillReceiveProps/UNSAFE_componentWillReceiveProps
    • componentWillUpdate/UNSAFE_componentWillUpdate
    • render之后ComponentDidUpdate之前,增加了getSnapshotBeforeUpdate钩子

2. <React.StrictMode>

这个高阶组件是用来检测一些老的api或者不安全的生命周期的使用,会给出相应的警告。文档portal

3.ref

  • createRef
  • forwardRef

React@16.6

  • React.memo
  • React.lazy
  • Suspense (配合react.lazy可以实现code-spliting

React@16.8

  • hooks

React@17.0

  • Concurrent Mode

小抄:

Data change without mutation

  • Easier Undo/Redo and Time Travel。保存引用就可以了。
  • tracking change…如果是基于之前的对象做改变,对比就可能需要遍历所有属性;但是如果传入新的对象,只需要比对引用就可以了
  • PureComponent时,更容易比对之后得出何时渲染。shouldComponentUpdate。
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享