【发布时间】:2021-03-27 04:53:01
【问题描述】:
我有简单的博客文章。我想将类重写为功能组件和钩子。 现在,我使用编辑/添加表单在页面的生命周期方法中获得了这个逻辑: 它工作正常。
componentDidUpdate(prevProps, prevState) {
if (this.props.match.params.id !== prevProps.match.params.id) {
if (prevProps.match.params.id) {
this.props.onUnload();
}
this.id = this.props.match.params.id;
if (this.id) {
return this.props.onLoad(userService.articles.get(this.id));
}
this.props.onLoad(null);
}
this.isLoading = false;
}
componentDidMount() {
if (this.id) {
this.isLoading = true;
return this.props.onLoad(userService.articles.get(this.id));
}
this.isLoading = false;
this.props.onLoad(null);
}
componentWillUnmount() {
this.props.onUnload();
}
shouldComponentUpdate(newProps, newState) {
if (this.props.match.params.id !== newProps.match.params.id) {
this.isLoading = true;
}
return true;
}
我把它全部改写成这样的钩子:
//componentDidMount
useEffect(() => {
if (id) {
setIsloading(true);
return props.onLoad(userService.articles.get(id));
}
setIsloading(false);
props.onLoad(null);
}, []);
useEffect(()=> {
prevId.current = id;
}, [id]
);
//componentDidUpdate
useEffect(() => {
//const id = props.match.params.id;
if (id !== prevId.current) {
if (prevId.current) {
props.onUnload();
}
if (id) {
return props.onLoad(userService.articles.get(id));
}
props.onLoad(null);
}
setIsloading(false);
});
//componentWillUnmount
useEffect(() => {
return props.onUnload();
}, []);
- 我收到错误 - “重新渲染太多。”在密码箱 完整代码:codesandbox
这很奇怪,但是在本地主机上没有错误“重新渲染太多。”
-
不知道如何处理我的类“shouldComponentUpdate”方法如何将其重写为钩子。尝试了“备忘录”,但不知道在这种情况下如何写。
-
无论如何我都遗漏了一些东西,因为这一切都不起作用 - 它没有正确更新表单字段。
如果您对 React hooks 有很好的了解,请提供帮助或提供一些建议 - 如何解决?
【问题讨论】:
-
阅读更多
useEffect钩子的工作原理。 reactjs.org/docs/… -
泰。我做到了,并且在我的代码中,当需要它时,我对 useEffect 有依赖关系。我错过了什么吗?
-
是的,我看到几个
useEffects 没有任何依赖关系。 -
这可能对您有所帮助? stackoverflow.com/questions/54551949/…
-
我只看到没有 deps 的“componentDidUpdate( )”,因为它应该每次都运行。我错了,它也应该有部门吗?
标签: javascript reactjs react-hooks