react-spring 如何用旁路设计赋能前端交互

848次阅读  |  发布于2年以前

前端开发存在大量处理用户交互的场景,对于 React 开发者来说要在处理复杂交互的同时保证可维护性和性能更是一大难点。react-spring 为我们处理此类场景提供了一种解决方案,通过学习它的思想我们还可以将类似做法推广到其它有类似需求的场景。

React Spring 是一个专注于拟真弹簧动效的动画库,稍加学习就可以写出高性能易维护的复杂动画。学过 React Native 的同学可能就会对 React Spring 的 API 有些熟悉,它的思想正是启发自前者内置并广泛使用的 Animated API:将动画实际的执行过程全部放在 旁路的副作用 之中,即在主流程之外独立执行带有副作用的动画逻辑。

先来看一段修改自官方示例的代码,这里只需要大概浏览一遍而不用深究每行的具体用途。这段代码实现了一个带有缩放动画的多图预览页面,触摸滑动超过一定距离会直接切换到下一页:

import { useRef } from 'react'
import { useSprings, animated } from '@react-spring/web'
import { useDrag } from '@use-gesture/react'
import clamp from 'lodash.clamp'
import styles from './styles.module.css'

const images = [/* ... */]

function Viewpager() {
  const index = useRef(0)
  const width = window.innerWidth
  const [props, api] = useSprings(images.length, i => ({
    x: i * width,
    scale: 1,
    display: 'block'
  }))
  const bind = useDrag(({ active, movement: [mx], cancel }) => {
    const absMx = Math.abs(mx)
    if (active && absMx > width / 3) {
      index.current -= mx / absMx
      index.current = clamp(index.current, 0, images.length - 1)
      cancel()
    }
    api.start(i => i < index.current - 1 || i > index.current + 1 ? {
      display: 'none'
    } : {
      x: (i - index.current) * width + (active ? mx : 0),
      scale: active ? 1 - absMx / width : 1,
      display: 'block'
    })
  })
  return (
    <div className={styles.wrapper}>
      {props.map(({ x, display, scale }, i) => (
        <animated.div className={styles.page} {...bind()} key={i} style={{ display, x }}>
          <animated.div style={{ scale, backgroundImage: `url(${images[i]})` }} />
        </animated.div>
      ))}
    </div>
  )
}

https://codesandbox.io/s/gifted-carlos-mkbonw?file=/src/App.tsx

这样的一个组件中其实潜藏着 主流程旁路副作用 的两套逻辑。

先将部分代码隐藏,这样我们看到的似乎是和传统 React 函数组件无异的逻辑,因为这部分主流程中不存在 State 操作,在没有其它因素引发重渲染的情况下还可以将它看作是一个 Stateless 的静态组件:

function Viewpager() {
  const index = useRef(0)
  const width = window.innerWidth
  const [props, api] = useSprings(images.length, i => ({
    x: i * width,
    scale: 1,
    display: 'block'
  }))
  const bind = useDrag((/* ... */) => {/* ... */})
  return (
    <div className={styles.wrapper}>
      {props.map(({ x, display, scale }, i) => (
        <animated.div className={styles.page} {...bind()} key={i} style={{ display, x }}>
          <animated.div style={{ scale, backgroundImage: `url(${images[i]})` }} />
        </animated.div>
      ))}
    </div>
  )
}

接下来主要关注 useDrag 相关的代码:

function Viewpager() {
  const index = useRef(0)
  /* ... */
  const [props, api] = useSprings(/* ... */)
  const bind = useDrag(({ active, movement: [mx], cancel }) => {
    const absMx = Math.abs(mx)
    if (active && absMx > width / 3) {
      index.current -= mx / absMx
      index.current = clamp(index.current, 0, images.length - 1)
      cancel()
    }
    api.start(i => i < index.current - 1 || i > index.current + 1 ? {
      display: 'none'
    } : {
      x: (i - index.current) * width + (active ? mx : 0),
      scale: active ? 1 - absMx / width : 1,
      display: 'block'
    })
  })
  /* ... */
}

这里的回调函数包含的是每帧动画的处理逻辑,大概包括:

再来看帧动画逻辑是如何绑定到具体的元素上的。

function Viewpager() {
  /* ... */
  const bind = useDrag((/* ... */) => {/* ... */})
  return (
    <div className={styles.wrapper}>
      {props.map(({ x, display, scale }, i) => (
        <animated.div className={styles.page} {...bind()} key={i} style={{ display, x }}>
          <animated.div style={{ scale, backgroundImage: `url(${images[i]})` }} />
        </animated.div>
      ))}
    </div>
  )
}

useDrag 生成的 bind 函数包含了处理用户输入所需的所有副作用,具体来说调用 bind 函数会返回一个包含 onPointerDown onKeyUp 等 DOM 事件的对象,通过将这个对象填充到元素的属性,在元素上发生的用户输入操作就会尽数被 @use-gesture/react 给接管。useDrag 会处理这些事件并将它们传递的数据进行加工、在合适的时机调用回调中的动画帧逻辑。

到目前为止看起来似乎和处理用户输入并修改 State 的一般方法并没有区别,接下来的关键点在于对 Animated API 的使用:

function Viewpager() {
  /* ... */
  const [props, api] = useSprings(images.length, i => ({
    x: i * width,
    scale: 1,
    display: 'block'
  }))
  const bind = useDrag((/* ... */) => {
    /* ... */
    api.start(i => {/* ... */})
  })
  return (
    <div className={styles.wrapper}>
      {props.map(({ x, display, scale }, i) => (
        <animated.div className={styles.page} {...bind()} key={i} style={{ display, x }}>
          <animated.div style={{ scale, backgroundImage: `url(${images[i]})` }} />
        </animated.div>
      ))}
    </div>
  )
}

这里 useSprings 根据 images 的数量生成了一组动画逻辑,api 对象包含了动画相关的 API 能力,props 实际的类型定义则是类似这样的一个、包含若干个元素属性对象的数组:

type IProps = {
  x: SpringValue<number>;
  display: SpringValue<string>;
  scale: SpringValue<number>;
}[];

这里 props 的每项元素的属性都不能直接传递给普通的组件,它们是经过 react-spring 包装的值并且只能传递给 animated 命名空间下导出的组件。这套流程的不同在于:

这样做的目的是让事件发生时,能够不改变 State 进而引发组件重渲染,而是只运行 useDrag 的回调函数。因为前者作为更大块粒度逻辑的函数执行开销往往更大,造成的子组件重渲染对性能的影响更是难以估计。

到现在就可以理清整套流程的运作基本如下:应用入口触发首次渲染,通过数据源生成 JSX 并在函数组件中管理基础的状态并启动控制动画的旁路逻辑。也就是说图中上半部的这部分主流程代码,因为不存在额外引发 React 组件重渲染的因素,所以理应会像 Stateless 组件一样只执行一次。而下半部分的旁路逻辑则应该在用户触发动画时高频率触发。实际测试下面代码的行为确实也符合这样的预期:

function Viewpager() {
  console.log('re-render.')  // 只执行一次
  /* ... */
  const bind = useDrag((/* ... */) => {
    console.log('handle on drag event.')  // 拖动时高频触发
    /* ... */
  })
  return (/* ... */)
}

React 的思想希望理想状态下的函数都不包含副作用,用户界面总是通过 UI = fn(State) 的纯函数计算得出,这样的设计能够带来很多收益。但现实往往没办法这样美好,于是 React 提供了诸如 VDOM 协调机制、useEffects 等方式希望可控高效地在组件中使用副作用。而 react-spring 做法则是将领域特定的副作用收敛到一处并绕过主流程执行,通过各种设计巧妙避免各类预期外行为。

一般在使用 React、Vue 这类前端库时需要注意避免使用超出控制的副作用(比如直接在函数组件顶层进行事件绑定)。react-spring 的 API 设计亮点还在于它复用了 React 现有的部分机制:

形式上 api.start(...) 的调用方式与 React 曾经通用的类组件范式 this.setState(...) 很相近。并且两者对值的更新都是需要通过内部调度决定时机,而不一定立刻作用到位。无关于 react-spring 的实际实现,这样做好处在于内部还可以将 “动画逻辑代码的执行” 和 “实际的渲染绘制帧” 的时机解绑,也就是说每秒 60 帧的动画实际可以只运行十几次动画逻辑,每次运行之间间隔的动画绘制可以通过 transtions 机制或是补间算法进行计算,来做到进一步的性能优化。

思想上类似小程序为了优化渲染性能而将部分逻辑放入与逻辑层隔离的视图层中执行。小程序的逻辑代码操作 DOM 需要经过视图框架并进行代价高昂的跨线程通讯、传统 React 做法会在副作用事件中修改 State 来引发重渲染进而改变 DOM。而两者的优化方案都是为了解决早前设计存在的性能问题而提出的、通过绕过主流程达成目的的旁路方案。

前文提到的 React Native 也是通过类似的方式,将声明式语法编写的动画逻辑全部放在 Native 线程上运行,从而绕过主流程三线程架构的通信开销获得明显的性能提升。

类似的设计还能在很多领域应用。例如处理网络请求的库为了优化性能,会选择避免进行系统调用。而是隔离内核操作到单独的进程,通过共享内存和轮询的方式与用户态应用传递数据包,进而避免应用产生用户态到内核态的切换开销。这部分具体可以参考:[绝对干货!初学者也能看懂的DPDK知识点解析]

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8