reactjs useEffect()和深度嵌套对象的数组

hi3rlvi2  于 2023-01-17  发布在  React
关注(0)|答案(1)|浏览(149)

每当arrayWithDeeplyNestedObjects发生更改时,我都会尝试调用useEffect()export default compose(...是脱机的第一个数据库的一部分(watermelonDB),并在数据库中有变化时更新arrayWithDeeplyNestedObjects。可以预期,每当arrayWithDeeplyNestedObjects变化时,useEffect()都会执行。但它不是。这是因为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的修改是在对xyid_arr的对象中完成的。arrayWithDeeplyNestedObjects的长度也可以改变。那里可能有更多(或更少)相同结构的对象。
如何在每次arrayWithDeeplyNestedObjects更改时调用useEffect()

kmpatx3s

kmpatx3s1#

试试这个:

useEffect(() => {
  console.log(new Date());
  const doSomething = async () => {
    ...
  };
  doSomething();
}, [JSON.stringify(arrayWithDeeplyNestedObjects)]);

相关问题