将 componentDidMount、componentDidUpdate 转换为钩子

时间:2021-08-01 15:36:49

标签: reactjs react-hooks

react hook world 的新手,试图通过编码来学习,我不确定这个 componentDidUpdate 把它放在哪里 useEffect 有什么建议吗? 这是我的代码:

componentDidMount() {
  if (!this.props.realGraph) {
    this.loadGraph();
  }
  
  this.refs.graphDiv.addEventListener("click", this.onClickGraphDiv, true);
}

discardGraph() {
  this.props.clearGraphData();
  this.loadGraph();
}

componentDidUpdate() {
  this._zoomConfig();
}

_zoomConfig = () => {
  const z = d3Select(`#graph-id-graph-wrapper`)
  .call(d3Zoom())
  .on("dblclick.zoom", null)
  .on("mousedown.zoom", null)
};

realGrpah 来自 mapStateToProps

这是我将它转换为钩子所做的,

useEffect(() => {
  if (!props.realGraph) {
    loadGraph();
  }
  
  refs.graphDiv.addEventListener("click", onClickGraphDiv, true);
  _zoomConfig();
}, []);


discardGraph() {
  props.dispatch(clearGraphData())
  loadGraph();
}

_zoomConfig = () => {
  const z = d3Select(`#graph-id-graph-wrapper`)
  .call(d3Zoom())
  .on("dblclick.zoom", null)
  .on("mousedown.zoom", null)
};

2 个答案:

答案 0 :(得分:2)

您可以使用在每次重新渲染时触发的单独效果:

// Approximately component did mount
useEffect(() => {
  if (!props.realGraph) {
    loadGraph();
  }  
  refs.graphDiv.addEventListener("click", onClickGraphDiv, true);
}, []);

// Approximately component did update
useEffect(() => {
  _zoomConfig();
})

现在,如果您不希望它在 first 渲染时触发,您可以创建一个对布尔值的引用,用于忽略初始安装,我认为这更类似于componentDidUpdate

// Approximately component did mount
useEffect(() => {
  if (!props.realGraph) {
    loadGraph();
  }  
  refs.graphDiv.addEventListener("click", onClickGraphDiv, true);
  _zoomConfig();
}, []);

// Approximately component did update
const isMounted = useRef(false);
useEffect(() => {
  if (!isMounted.current) {
    isMounted.current = true;
  } else {
    _zoomConfig();
  }
})

答案 1 :(得分:0)

我也不是反应方面的超级专家,但以下解决方案可能对您的场景有用 -

<块引用>

对于 DidMount,用例非常简单 -

useEffect(() => {
    // your code
}, []); // passing an empty dependency array will fire it only for the first time when component renders
<块引用>

为了实现 DidUpdate,您可以将一个 prop 从您的父组件传递到您当前的组件并触发该 prop 更新的效果,如下所示 -

例如,您在父组件中使用此组件作为 -

const [updateZoom, setUpdateZoom] = useState(0);    // using this to update child component

// handleZoom on some event
const handleZoom = () => {
    setUpdateZoom(uz => uz + 1);
}

return (
    <GraphComponent realGraph={realGraph} clearGraphData={clearGraphData} updateZoom={updateZoom} />
);

并在您的当前/子组件中使用 updateZoom 如下 -

useEffect(() => {
    console.log('updateZoom did update');
    this._zoomConfig();
}, [updateZoom]);