我只想在productType
改变时执行我的useEffect
方法中的代码,一旦页面加载,我就能识别出console.log被执行了6-7次以上,这是我不想要的。
下面是我的代码摘要:
const [productType, setProductType] = useState(null);
useEffect(() => {
console.log(productType);
}, productType);
我的想法是在productType
更改时在此useEffect
中执行代码,我在下拉列表中更改它,如下所示:
<MyDropdownComponent
value={productType}
onChange={e => setExportType(e.target.value)}
width={200}
/>
所以我想知道为什么当我加载这个视图/模板时,我在我的控制台上得到了6-7-8 console.logs
of null
。
发布于 2019-09-02 16:36:47
useEffect挂钩需要一个数组作为第二个参数。他们这样做可能是为了区分空数组(只运行一次效果)和默认数组(在每次渲染时运行),如果他们直接使用arguments
,则不会有默认数组。
您需要像这样传递一个数组:
useEffect(() => {
console.log(productType);
}, [productType]);
https://stackoverflow.com/questions/57753736
复制相似问题