React hooks:如何在类组件中在构造函数中初始化的函数组件中编写变量

tin*_*ing 13 reactjs react-hooks

我在 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} />
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

  return <StatusBar uppy={uppy} />
}
Run Code Online (Sandbox Code Playgroud)

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

Shu*_*tri 13

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

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

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

  return <StatusBar uppy={uppy.current} />
}
Run Code Online (Sandbox Code Playgroud)