问题描述
我正在将我的反应代码从类转换为钩子
我以前有这样的东西
export default class Editor extends React.Component {
constructor(props) {
super(props)
this.state = this.getStateObject()
}
getStateObject() {
const { page } = this.props
return {
label: page.label || '',session: page.session || false
}
}
componentDidUpdate(prevProps) {
if (!_.isEqual(this.props.projects,prevProps.projects)) {
this.setState(this.getStateObject())
}
}
在尝试转向功能时,我做了类似的事情
export default function tabeditor ({page}:Page) {
const [appPageInfo,setAppPageInfo] = useState({
label: page.label || '',session: page.session || false
})
/* Equivalence in hooks
componentDidUpdate(prevProps) {
if (!_.isEqual(this.props.projects,prevProps.projects)) {
this.setState(this.getStateObject())
}
}
*/
const handleOnClickUpdate = () => {
updateMobileAppPage(Object.assign({},page,appPageInfo))
close()
}
但是我无法确定React钩子中componentDidUpdate
的等效性。
解决方法
您可以使用useEffect
钩子添加projects
道具作为依赖项,如下所示:
useEffect(() => {
// Whatever code you want to run if props.projects change
},[props.projects]);
,
要模仿Hooks中的componentDidUpdate,请使用useEffect,然后传入条件参数,只要参数更改,useEffect便会与该条件参数一起运行。下面的例子
useEffect(() => {
.......
//This useEffect will re-run whenever the parameter in the square bracket updates/changes.
},[parameter])