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

问题描述 投票:1回答:2

我尝试为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)
    })
  }
reactjs react-router react-hooks
2个回答
1
投票

由于您只希望在初始渲染时调用history.listen并在卸载时清理侦听器,因此可以使用useEffect作为依赖关系数组调用​​empty array并返回清理函数

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了解更多详情


1
投票

试试这个吧。

import React, { useEffect } from 'react';

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

in useEffect我们正在使用[]。 []类似于componentDidMount。

现在,如果您想使用componentDidUpdate,则需要在[]中传递状态。

对于前。如果count更新,那么您想要更改任何内容,请查看此代码。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.