javascript - 如何重写部分组件以响应钩子
问题描述
告诉我,我想重写写在钩子上的生命周期方法上的组件,但它并没有完全出现在这个地方,它不能正常工作。如何正确改写?
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)
解决方案
我已经修改了反应新的钩子,
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])
推荐阅读
- swift - 对于每个未正确显示的空数组
- metafor - 与图文本重叠的森林图
- arrays - 使用自定义对象内联初始化和填充数组
- c# - 使用 DataTable.Compute() 方法比较 C# Visual Studio 中的两个变量
- python - 连接没有唯一键的列并在新列中写下非唯一组合
- python - 无法使用 pymysql 将数据文件加载到 MySQL - 找不到文件
- windows - CListCtrl (MFC) 将 MouseWheel 事件转换为“所选项目已更改”通知
- javascript - 无法使用 Javascript 在 Google 表单上设置输入值
- spring - Spring @Transactional - 通过 AspectJ 同步
- sql-server - Powershell将管道返回值存储到变量