![](/img/trans.png)
[英]Is that safe to use functional components with hooks inside class based components in React?
[英]React hooks: How to write variables in functional components that in class components were initialized in the constructor
我在React中使用uppy,它们通常将uppy初始化为全局变量。 在React中,他们允许这样做:
class MyComponent extends React.Component {
constructor (props) {
super(props)
this.uppy = Uppy()
.use(Transloadit, {})
}
componentWillUnmount () {
this.uppy.close()
}
render () {
return <StatusBar uppy={this.uppy} />
}
}
如何在带有钩子的功能组件中编写此代码? 幼稚的方法如下(在阅读了此问题后,没想到它会起作用):
const MyComponent = () => {
const uppy = Uppy()
.use(Transloadit, {})
useEffect(() => {
return () => uppy.close()
})
return <StatusBar uppy={uppy} />
}
PS:这需要在功能组件内部完成,因为我在uppy.use
方法中使用了一些道具。
可以使用useRef
钩子初始化功能组件中的变量( 在此处阅读更多)。 另外,由于您只想在卸载时而不是在每次重新渲染时运行cleanup函数,因此应该将空[]
作为useEffect
的第二个参数useEffect
const MyComponent = () => {
const uppy = useRef(Uppy()
.use(Transloadit, {}))
useEffect(() => {
return () => uppy.current.close()
}, [])
return <StatusBar uppy={uppy.current} />
}
您可以这样实现。
> const MyComponent = (props) => { let uppy;
>
> useEffect(() => {
> uppy = Uppy()
> .use(Transloadit, {});
> return () => uppy.close() }, [])
>
> return <StatusBar uppy={uppy} /> }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.