【问题标题】:useEffect() and array of deeply nested objectsuseEffect() 和深度嵌套对象数组
【发布时间】:2023-01-13 03:23:51
【问题描述】:

每当arrayWithDeeplyNestedObjects 发生变化时,我都会尝试致电useEffect()export default compose(... 是离线优先数据库 (watermelonDB) 的一部分,并在数据库发生变化时更新 arrayWithDeeplyNestedObjects。人们可以期望 useEffect()arrayWithDeeplyNestedObjects 更改时执行,但事实并非如此。这是因为 useEffect() 只执行浅层比较,不识别 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 () => {
        ...
    };
    doSomething();
  }, [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);

这就是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()

【问题讨论】:

    标签: javascript reactjs arrays react-hooks watermelondb


    【解决方案1】:

    尝试这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-12
      • 2019-01-29
      • 2016-05-18
      • 1970-01-01
      • 2016-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多