【发布时间】:2021-03-02 03:16:47
【问题描述】:
根据React docs:
效果函数中引用的每个值也应该出现在依赖项数组中
如果我的效果函数从外部范围引用了一些变量,但我只想在其中一个发生变化时执行它,为什么我需要在依赖数组中指定所有其他变量?是的,如果其他变量发生变化,闭包将变得陈旧,但我不在乎,因为我还不需要调用该函数。当我关心的变量发生变化时,可以调用具有当时值的新闭包。我错过了什么?
这是一个工作示例(据我所知),其中 useEffect 依赖数组并不详尽:
import React, { useEffect, useState } from "react";
const allCars = {
toyota: ["camry", "corolla", "mirai"],
ford: ["mustang", "cortina", "model T"],
nissan: ["murano", "micra", "maxima"],
};
function CarList() {
const [cars, setCars] = useState([]);
const [brand, setBrand] = useState("toyota");
const [filterKey, setFilterKey] = useState("");
useEffect(() => {
// I don't want to run this effect when filterKey changes because I wanna wrap that case in a timeout to throttle it.
setCars(allCars[brand].filter(model => model.startsWith(filterKey)));
}, [brand]);
useEffect(() => {
// This effect is only called when filterKey changes but still picks up the current value of 'brand' at the time the function is called.
const timeoutId = setTimeout(() => {
setCars(allCars[brand].filter(model => model.startsWith(filterKey)));
}, 500);
return () => clearTimeout(timeoutId);
}, [filterKey]);
const handleChangeFilterKey = event => {
setFilterKey(event.target.value);
};
return (
<div>
{`${brand} cars`}
<div>Select brand</div>
<input type="radio" value="toyota" checked={brand === "toyota"} onChange={() => setBrand("toyota")} />
<input type="radio" value="ford" checked={brand === "ford"} onChange={() => setBrand("ford")} />
<input type="radio" value="nissan" checked={brand === "nissan"} onChange={() => setBrand("nissan")} />
<div>Filter</div>
<input label="search" value={filterKey} onChange={handleChangeFilterKey} />
<ul>
{cars.map(car => (
<li>{car}</li>
))}
</ul>
</div>
);
}
上面的例子有什么陷阱吗?
【问题讨论】:
-
不,代码可以在不详尽的情况下工作 - 但通常建议详尽。
-
不,一点也不。实际上,您可以使用完全空的依赖数组来指示效果应该在组件挂载时只运行一次。
-
所以这两个效果都会运行第一个渲染,对吧?不是终端,但效率低下......
标签: reactjs react-hooks