使用 React 钩子时如何初始化第三方库?

dan*_*yyy 6 reactjs react-hooks

如果我有一个第三方库,我通常会像这样初始化:

class App {
  constructor(props) {
    this.helperLibrary = new HelperLibrary();
    this.state = { data: null };
  }
}
Run Code Online (Sandbox Code Playgroud)

我将如何使用 React 钩子在功能组件中初始化它?

所以更新后的代码看起来像:

const App = () => {
  const [data, setData] = useState(null);

  // Would I write something like this here??
  helperLibrary = new HelperLibrary();

  // Or would I use something like useEffect since
  // constructor runs when the component is created?

  useEffect = (() => {
    helperLibrary = new HelperLibrary();
  }, []);
};
Run Code Online (Sandbox Code Playgroud)

Apr*_*ion 6

一种简单的方法是在组件外部初始化:

const helperLibrary = new HelperLibrary();

const App = () => {
  const [data, setData] = useState(null);
};
Run Code Online (Sandbox Code Playgroud)


如果你需要有条件地初始化它,就在App第一次渲染之前(而不是在不同的路由中),最接近的构造函数将是这样的:

const App = () => {
  const helperLibrary = useRef(null);
  const [data, setData] = useState(null);

  // note: useEffect would run AFTER first render, equivalent of componentDidMount,
  //       for equivalent of consturctor, we need sync code, e.g.:
  if (!helperLibrary.current) {
    helperLibrary.current = new HelperLibrary();
  }
};
Run Code Online (Sandbox Code Playgroud)