【问题标题】:How to implement a hook for componentDidMount with react-router?如何使用 react-router 实现 componentDidMount 的钩子?
【发布时间】:2019-08-24 11:56:47
【问题描述】:
我正在尝试为我的 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
【解决方案1】:
试试这个。
import React, { useEffect } from 'react';
useEffect(() => {
// all your code that you put in componentDidMount method
}, [])
在 useEffect 中我们使用 []。 [] 类似于 componentDidMount。
现在如果你想使用 componentDidUpdate 那么你需要在 [] 中传递状态。
例如。如果当时计数是更新的,您想更改任何内容,请查看此代码。
useEffect(() => {
// all your code goes here related to count state.
}, [count])
所以如果计数发生变化,上面的代码将触发重新渲染,否则它不会调用。
【解决方案2】:
由于您只希望在初始渲染时调用 history.listen 并在卸载时清理侦听器,因此您可以使用 empty array 作为依赖数组调用 useEffect 并返回清理函数
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了解更多详情