react hooks的闭包问题

春节之后,最大的新闻,就是 react hooksalpha 版本变成了正式版本,所以迫不及待的尝试一波,准备后续直接运用到后续的产品中。下面记录了使用过程中遇到的一个闭包的问题。

在以前的开发过程中用到很普遍的场景就是从服务端拿数据,一般来说,在hooks之前,请求的发送位置都在componentDidMount 里面,至于为什么这里就不再赘述,相信网上很多地方都有提到。

现在换成hooks之后,目前来说最佳请求数据的地方应该在useEffect中,像这样

function DemoComponent(props) {
  useEffect(() => {
    fetchData().then((data) => {
      // some operate for data
    })
  }, [])
}

最后的数据需要响应到界面上所以我们还需要用一个state来管理, 像这样

function DemoComponent(props) {
  const [name, setName] = useState('name')
  const [age, setAge] = useState(10)
  useEffect(() => {
    fetchData().then((data) => {
      // some operate for data
     setName(data.name)
     setAge(data.age)
    })
  }, [])
}

到目前为止看不出太大的问题,继续

在实际业务中有可能字段很多,所以再考虑是否能像以前class components 一样用一个对象来管理所有的state。所以代码改成这样

function DemoComponent(props) {
  const [state, setState] = useState({ name: 'name', age: 10 })
  useEffect(() => {
    fetchData().then((data) => {
      // some operate for data
      setState({
        name: data.name,
        age: data.age
      })
    })
  }, [])
}

运行结果似乎也没有什么问题。接下来我们再加另外一个请求

function DemoComponent(props) {
  const [state, setState] = useState({ name: 'name', age: 10, count: 0 })
  useEffect(() => {
    fetchData().then((data) => {
      // some operate for data
      setState({
        name: data.name,
        age: data.age
      })
    })
    fetchCount().then((count) => {
      setState({
        count: count
      })
    })
  }, [])
}

结果总会有一个结果被覆盖掉,不符合预期。后面发现是因为这里的setState虽然改成了对象,但是它并不会像class components那样帮你自动合并前面的state

Note
Unlike the setState method found in class components, useState does not automatically merge update objects

粘贴来自官方文档,所以这里需要手动合并,像这样

function DemoComponent(props) {
  const [state, setState] = useState({ name: 'name', age: 10, count: 0 })
  useEffect(() => {
    fetchData().then((data) => {
      // some operate for data
      setState({
        ...state,
        name: data.name,
        age: data.age
      })
    })
    fetchCount().then((count) => {
      setState({
        ...state,
        count: count
      })
    })
  }, [])
}

这样改正之后按道理就应该符合我们的预期了,运行后发现,还是后响应的会把前一个响应的给覆盖了,这里附上demo链接https://codesandbox.io/s/k61zml7rr

难道是state异步更新的问题?

function DemoComponent(props) {
  const [state, setState] = useState({ name: 'name', age: 10, count: 0 })
  console.log(state)
  useEffect(() => {
    fetchData().then((data) => {
      // some operate for data
      setState({
        ...state,
        name: data.name,
        age: data.age
      })
    })
    fetchCount().then((count) => {
      setState({
        ...state,
        count: count
      })
    })
  }, [])
}

打印查看后,state其实是已经更新过的。

最后排查发现就是因为在useEffect里面依赖了preState, 但是在每一次更新后,其实useState返回的state指向是一个新的对象,所以useEffect里面由于闭包的原因,引用的是最初始的state对象,所以这样的合并的还是最初始的state,导致现在的结果。

官方后续新增了https://github.com/facebook/react/pull/14636 eslint规则来检查这样旧的闭包依赖。从而提醒我们在写的过程中避免这样的依赖问题。

像我们上述的这样的情况,要让state保持最新的方法有,
一、useEffect的callBack多次执行,这样显然不符合我们的预期,因为数据初始化请求往往只需要一次
二、避免对外部变量的依赖,但是又要拿到最新的preState,官方文档中还有提到的functional-updates。这样就可以避免对外部变量的引用了。

该文章是问了记录自己在使用hooks的时候遇到的坑,有可能这个场景你不会覆盖到,但是这样问题的本质反应出了hooks闭包应用问题。Dantwitter中有提到后续数据获取会有新的解决方案就是Suspense,

最后

hooks给我们带来了一种新的编程方式,也给我们带来更多的可能,目前社区已衍生出很多好用的自定义hooks。引用Dan的一段话

React is not really a language. But its innovation is very language-like: functions that can have tree-based local state and effects, but are invoked like functions.
Classes and plain functions are an approximation of this model. Functions with Hooks are a closer approximation.

其他

部分三方自定义hooks的库也有同样的问题,选取了当前star较多的react-use进行了修复https://github.com/streamich/react-use/pull/112

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容