【发布时间】:2020-03-24 14:38:09
【问题描述】:
我想在钩子中实现componentDidMount,我想为第一次渲染做一些事情ONLY,所以在useEffect中,我将依赖数组设置为空,但eslint有警告缺少依赖项。
如何解决?
import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";
const Child = ({ age }) => {
useEffect(() => {
console.log("simulate componentDidMount, age:", age);
}, []);
useEffect(() => {
console.log('simulate componentDidUpdate, age:', age)
}, [age])
return <div>age: {age}</div>;
};
const App = () => {
const [age, setAge] = useState(0);
const handleOnClick = e => {
e.preventDefault();
setAge(a => a + 1);
};
return (
<>
<Child age={age} />
<button onClick={handleOnClick}>INCREASE AGE</button>
</>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
【问题讨论】:
标签: reactjs react-hooks eslint