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

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} />
  }
}

如何在带有钩子的功能组件中编写它?天真的做法是这样的(没想到看了this issue后还能用):

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

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

  return <StatusBar uppy={uppy} />
}

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

功能组件中的变量可以使用 useRef 挂钩进行初始化(阅读更多内容 here)。此外,由于您只想 运行 卸载而不是每个 re-render 上的清理功能,您应该将空的 [] 作为第二个参数传递给 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} /> }