首页 > 解决方案 > 如何重写部分组件以响应钩子

问题描述

告诉我,我想重写写在钩子上的生命周期方法上的组件,但它并没有完全出现在这个地方,它不能正常工作。如何正确改写?

componentDidMount() {
    this.updateUser();
}
componentDidUpdate(prevProps){
    if (this.props.userId !== prevProps.userId) {
        this.updateUser();
        console.log('update')
    }
}

updateUser = () => {
    const {userId} = this.props;
    if (!userId) {
        return;
    }
    this.onUserLoading();
    this.API
            .getUser(userId)
            .then(this.onUserLoaded)
            .catch(this.onError)

标签: javascriptreactjsreact-reduxreact-hooks

解决方案


我已经修改了反应新的钩子,

componentDidMount手段useEffect(()=>{},[]) componentDidUpdate手段useEffect((prev)=>{},[YOUR UPDATE DATA VARIABLE])

现在看起来像这样,您的功能如下所示,

updateUser = () => {
  if (!userId) {
      return;
  }
  this.onUserLoading();
  this.API
          .getUser(userId)
          .then(this.onUserLoaded)
          .catch(this.onError)
}

这将被转换为功能组件,

const [userId,setUserId] = useState(props.userId); // way 1
//const userId = {props}; // way 2

useEffect((prevProps)=>{
  updateUser();
  if(userId !== prevProps.userId){
    updateUser();
    console.log('update')
  }

},[userId, updateUser])  

推荐阅读