如何使用 react-router 实现 componentDidMount 的钩子?

How to implement a hook for componentDidMount with react-router?

我正在尝试为我的 componentDidMount 实现 useEffect,但我不知道在这种情况下该怎么做:

 componentDidMount() {
    logNavego(this.props.history.location.pathname + 
    this.props.history.location.search )
    this.unlisten = this.props.history.listen(location => {
      logNavego(location.pathname + location.search)
    })
  }

试试这个。

import React, { useEffect } from 'react';

useEffect(() => {
  // all your code that you put in  componentDidMount method
}, [])

in useEffect we're using []. that [] is similar to componentDidMount.

现在如果你想使用 componentDidUpdate 那么你需要在 [].

中传递状态

例如。如果当时计数已更新,您想更改任何内容,请参阅此代码。

useEffect(() => {
  // all your code goes here related to count state.
}, [count])

所以如果计数发生变化,上面的代码将触发重新渲染,否则它不会调用。

由于您只想在初始渲染时调用 history.listen 并在卸载时清理侦听器,因此您可以调用 useEffect 并将 empty array 作为依赖项数组并 return 清理函数

useEffect(() => {
    logNavego(props.history.location.pathname + props.history.location.search )
    const unlisten = props.history.listen(location => {
      logNavego(location.pathname + location.search)
    });
    return () => {
       unlisten();
    }
  }, [])

详情可参考useEffect docs