【发布时间】:2020-08-06 21:32:27
【问题描述】:
大家好,给定一个基本的反应组件,它有componentWillReceiveProps。我想将其转换为使用反应钩子。现在我已经查看了这个问题here,虽然答案很简单,但我觉得我好像错过了一些理解。例如:
export class Example extends React.Component {
constructor(props) {
super(props);
}
componentWillReceiveProps(nextProps) {
console.log('HELLO WORLD') // Note this isn't called on initial render
if (nextProps.match.params.id != this.props.match.params.id) {
console.log('testing....')
}
}
render() {
return (
<div>Cool</div>
);
}
}
我从上面的例子中知道,除非 nextProps 没有改变,否则我们不会进入 if 语句。现在将上面的转换为函数组件是这样的:
export const Example = ({ ...props }) => {
useEffect(() => {
console.log('TESTING')
}, [props.match.params.id])
return (
<div>Cool</div>
)
}
我还准备了我所见内容的简短记录 gif。 https://recordit.co/hPuwGey6WM
【问题讨论】:
-
要添加依赖项,您需要使用数组。
useEffect(function(0 {}, [props.match.params.id]);话虽如此,我认为它总是会在第一次渲染时运行 -
@SerShubham - 抱歉,即使使用数组语法,你也是对的,我看到了同样的事情。你会在录音中看到这一点。
-
useEffect总是在第一次挂载时运行 -
对.. 那么我该如何正确模拟:
componentWillReceiveProps的行为。因为这不会在第一次挂载时运行。 -
@Jagrati - 我知道如果你不想在第一次挂载时运行效果,你必须传入一个空数组来使用效果。但这意味着我不会观察任何属性。
标签: reactjs react-hooks