React hooks:如何在类组件中在构造函数中初始化的函数组件中编写变量 [英] React hooks: How to write variables in functional components that in class components were initialized in the constructor

查看:482
本文介绍了React hooks:如何在类组件中在构造函数中初始化的函数组件中编写变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 React 中使用 uppy,它们通常将 uppy 初始化为全局变量.在 React 中,他们允许这样做:

I'm using uppy with React and they normally initialize uppy as a global variable. In React, they allow to do this instead:

class MyComponent extends React.Component {
  constructor (props) {
    super(props)
    this.uppy = Uppy()
      .use(Transloadit, {})
  }

  componentWillUnmount () {
    this.uppy.close()
  }

  render () {
    return <StatusBar uppy={this.uppy} />
  }
}

如何在带有钩子的功能组件中编写此内容?天真的方法如下(在阅读这个问题后没想到它会起作用)):

How do I write this in a functional component with hooks? The naive approach would be the following (didn't expect it to work after reading this issue):

const MyComponent = () => {
  const uppy = Uppy()
    .use(Transloadit, {})

  useEffect(() => {
    return () => uppy.close()
  })

  return <StatusBar uppy={uppy} />
}

PS:它需要在功能组件内部完成,因为我在 uppy.use 方法中使用了一些道具.

PS: It needs to be done inside of the functional component because I'm using some props in an uppy.use method.

推荐答案

功能组件中的变量可以使用 useRef 钩子初始化(阅读更多 此处).此外,由于您只想在卸载时运行清理函数而不是在每次重新渲染时运行,因此您应该将一个空的 [] 作为第二个参数传递给 useEffect

Variables in functional components can be initialized using useRef hook (read more here). Also since you only want to run the cleanup function on unmounting and not on every re-render, you should pass an empty [] as the second argument to useEffect

const MyComponent = () => {
  const uppy = useRef(Uppy()
    .use(Transloadit, {}))

  useEffect(() => {
    return () => uppy.current.close()
  }, [])

  return <StatusBar uppy={uppy.current} />
}

这篇关于React hooks:如何在类组件中在构造函数中初始化的函数组件中编写变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆