我有一个使用钩子的功能组件:
function Component(props) {
const [ items, setItems ] = useState([]);
// In a callback Hook to prevent unnecessary re-renders
const handleFetchItems = useCallback(() => {
fetchItemsFromApi().then(setItems);
}, []);
// Fetch items on mount
useEffect(() => {
handleFetchItems();
}, []);
// I want this effect to run only when 'props.itemId' changes,
// not when 'items' changes
useEffect(() => {
if (items) {
const item = items.find(item => item.id === props.itemId);
console.log("Item changed to " item.name);
}
}, [ items, props.itemId ])
// Clicking the button should NOT log anything to console
return (
<Button onClick={handleFetchItems}>Fetch items</Button>
);
}
该组件在挂载时获取大约items
个,并将它们保存到状态.
组件接收itemId
props (来自React路由).
每当props.itemId
改变时,我希望它触发一个效果,在本例中,将其记录到控制台.
问题是,由于效果也依赖于items
,因此每当items
发生变化时,效果也会运行,例如当按下按钮重新获取items
时.
这可以通过将之前的props.itemId
个变量存储在一个单独的状态变量中并比较这两个变量来解决,但这似乎是一个黑客攻击,并添加了样板文件.通过比较componentDidUpdate
中当前和以前的props ,使用组件类可以解决这个问题,但是使用功能组件是不可能的,这是使用挂钩的一个要求.
What is the best way to trigger an effect dependent on multiple parameters, only when one of the parameters change?
PS. Hooks are kind of a new thing, and I think we all are trying our best to figure out how to properly work with them, so if my way of thinking about this seems wrong or awkward to you, please point it out.