[英]useEffect() and array of deeply nested objects
每当arrayWithDeeplyNestedObjects
发生变化时,我都会尝试调用useEffect()
。 export default compose(...
是离线第一个数据库 ( watermelonDB ) 的一部分,并在数据库发生变化时更新arrayWithDeeplyNestedObjects
。人们可以期望useEffect()
在arrayWithDeeplyNestedObjects
发生变化时执行,但事实并非如此。这是因为useEffect()
仅执行 shallo 比较,不识别arrayWithDeeplyNestedObjects
中的更改。
import withObservables from '@nozbe/with-observables';
import {withDatabase} from '@nozbe/watermelondb/DatabaseProvider';
import {compose} from 'recompose';
import {Q} from '@nozbe/watermelondb';
const Foo = ({arrayWithDeeplyNestedObjects}) => {
console.log('render'); // <-- this renders whenever arrayWithDeeplyNestedObjects is updated
useEffect(() => {
console.log(new Date()); // <-- this does not render whenever arrayWithDeeplyNestedObjects is updated
const doSomething = async () => {
...
};
const data = await doSomething();
setData(data);
}, [arrayWithDeeplyNestedObjects]); // <-- this does only perform a shallow compare
return <SomeNiceUi />
}
export default compose(
withDatabase,
withObservables(['arrayWithDeeplyNestedObjects'], ({database}) => ({
arrayWithDeeplyNestedObjects: database.get(SOME_TABLE).query().observe(),
})),
)(Foo); <-- subscription das fires everytime an update is made to the database
这就是arrayWithDeeplyNestedObjects
的样子
[{"__changes": null, "_isEditing": false, "_preparedState": null, "_raw": {"_changed": "x,y", "_status": "created", "id": "3", "x": 5851, "id_arr": "[\"160\"]", "id": "6wmwep5xwfzj3dav", "y": 0.17576194444444446}, "_subscribers": [], "collection": {"_cache": [RecordCache], "_subscribers": [Array], "changes": [Subject], "database": [Database], "modelClass": [Function SomeTable]}}]
对arrayWithDeeplyNestedObjects
的更改是在x
、 y
或id_arr
的对象中完成的。 arrayWithDeeplyNestedObjects
的长度也可以改变。 那里可能有更多(或更少)相同结构的对象。
每次arrayWithDeeplyNestedObjects
更改时如何调用useEffect()
?
尝试这个:
useEffect(() => {
console.log(new Date());
const doSomething = async () => {
...
};
doSomething();
}, [JSON.stringify(arrayWithDeeplyNestedObjects)]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.