[英]converting componentDidUpdate componentDidMount to hooks
Learning react by coding, trying to convert this code into hooks version, but i'm not getting any error and still code is not working ( class version works), just want to have some advice or help if i have converted it in right way or not?学习通过编码做出反应,尝试将此代码转换为钩子版本,但我没有收到任何错误并且代码仍然无法正常工作(class 版本有效),如果我以正确的方式转换它,只想获得一些建议或帮助或不?
english is not my mother language so could be mistakes.英语不是我的母语,所以可能是错误的。
class: class:
componentDidMount() { this.updateCanvas(); const img = this.refs.CameraImage; img.onload = this.updateCanvas.bind(this); } componentDidUpdate(prevProps, prevState, snapshot) { this.updateCanvas(); } componentWillUnmount() { clearInterval(this.snapshotInterval); }
converted version:转换版本:
useEffect(() => { updateCanvas(); const img = CameraImage.current; img.onload = updateCanvas; return () => { img.onload = null; }; });
You are right according to React docs about hooks :根据 关于 hooks 的 React 文档,你是对的:
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
And an example of converted componentWillUnmount
to hooks :以及将
componentWillUnmount
转换为hooks的示例:
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
// Specify how to clean up after this effect:
return function cleanup() {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});
And code would like this:代码会是这样的:
useEffect(() => {
// componentDidMount run once when the component is mounted
this.updateCanvas();
const img = refs.CameraImage;
img.onload = updateCanvas;
// will be called on component unmount
return () => {
clearInterval(this.snapshotInterval);
}
})
1 - you didn't pass an array into the useEffect Hook
, so your component will continuously reload repeatedly. 1 -您没有将数组传递给
useEffect Hook
,因此您的组件将不断重复重新加载。
2 - if you pass an empty array, then you are not watching any variables, and therefore it will only update the state on the first render, exactly like componentDidMount
. 2 -如果你传递一个空数组,那么你没有观察任何变量,因此它只会在第一次渲染时更新 state,就像
componentDidMount
一样。 in your case you are watching snapshot variable so add it as a dependency.在您的情况下,您正在观看快照变量,因此将其添加为依赖项。 So just change your code like this:
所以只需像这样更改您的代码:
useEffect(() => {
updateCanvas();
const img = CameraImage.current;
img.onload = updateCanvas;
return () => {
img.onload = null;
};
}, [snapshot]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.