问题描述
我在 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:如何在类组件中在构造函数中初始化的函数组件中编写变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!