React hooks组件确实使用prevProps更新

问题描述

我正在将我的反应代码从类转换为钩子

我以前有这样的东西

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])

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...