React hooks - 当对象集合中的嵌套属性发生变化时触发 useEffect [英] React hooks - trigger useEffect when a nested property changes in a collection of objects

查看:28
本文介绍了React hooks - 当对象集合中的嵌套属性发生变化时触发 useEffect的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

页面显示对象列表[{name:, age:}, ...]第二页允许更新特定对象的名称.然后使用钩子,我应该如何实现 useEffect() 以便仅在检测到名称更改时才更新首页上的列表?

A page displays a list of objects [{name:, age:}, ...] A second page allows to update the name of a particular object. Then using hooks, how should I implement useEffect() so the list on the front page updates only when a name change has been detected?

const [objects, setObjects] = useState([]);

useEffect(()=> {
  getAllObjects()
},[getAllObjects, objects]);

推荐答案

不要将整个对象传递给依赖项数组,请确保只传递名称.您可以通过返回名称来完成

Instead of passing the entire object to the dependency array, make sure that you only pass name. Which you can do by returning the names

const [objects, setObjects] = useState([])

useEffect(()=> {
      getAllObjects()
}, [getAllObjects, ...objects.map(item => item.name)])

这篇关于React hooks - 当对象集合中的嵌套属性发生变化时触发 useEffect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆