如何从 ImmutableJS Record 构造函数调用函数

How to call a function from ImmutableJS Record constructor

我已经用不可变记录替换了我的打字稿实体中的 many/most 以达到一定程度的 safety/security/warm 和模糊,但我只是注意到我的构造函数现在已损坏。

最初,我在我的构造函数中自动创建新的 UUID 作为默认值,但是使用 ImmutableJS 记录 - 这种行为被打破了。

我明白为什么,但我不完全确定正确的解决方法是什么 - 但我觉得它要么非常复杂,要么非常简单。

import { Record } from "immutable";
import uuid from "uuid";

const tagDefaults: TagParams = {
    depth: 0,
    id: "tag::" + uuid.v4(),
    name,
    order: 0,
};

interface TagParams {
    name: string;
    order: number;
    depth: number;
    id: string;
}

export class Tag extends Record(tagDefaults) { }

创建初始 tagDefaults 是创建第一个 UUID 的原因 - 之后,所有后续新 Tag() 使用相同的 ID。

有没有一种简单的方法可以在每个构造函数上调用一个函数?我试过在构造函数中重写 (this.id = uuid.v4()) 但这实际上导致 Webpack 对我造成伤害。

更新:2018 年 6 月 8 日

使用@mpontus 提供的答案,这是一个更新的示例,显示任一选项都可以工作。

import { Record, Set } from "immutable";
import uuid from "uuid";

const tagDefaults: TagParams = {
    depth: 0,
    id: "",
    name,
    order: 0,
};

interface TagParams {
    name: string;
    order: number;
    depth: number;
    id: string;
}

export class Tag extends Record(tagDefaults) {
    constructor(props: Partial<TagParams> = {}) {
        // Option A - Works
        if (!props.id) {
            props.id = uuid.v4();
        }

        super(props);

        // Option B - Works
        // if (!this.id) {
        //     return this.set("id", uuid.v4());
        // }
        // return this;
    }
}

describe("Given a Tag", () => {
    describe("When constructed", () => {
        test("It should contain a unique id", () => {
            const tag1 = new Tag();
            const tag2 = new Tag({});
            const tag3 = new Tag({ depth: 1, name: "hello", order: 10 });
            const tag4 = new Tag({ id: "tag4Id" });
            const tags = Set([tag1, tag2, tag3, tag4].map((t) => t.id));
            expect(tags.size).toBe(4);
            console.log([tags]);
        });
    });
});

您无法使用默认值完成您想要的。

您覆盖 Tag 构造函数的尝试很好,但您必须覆盖进入构造函数的值:

const tagDefaults = {
    depth: 0,
    id: "",
    name: "",
    order: 0,
};

class Tag extends Record(tagDefaults) {
    constructor(values) {
        const finalValues = { ...values };

        if (finalValues.id === undefined) {
            finalValues.id = uuid.v4();
        }

        super(finalValues);
    }
}

或者,您可以 return 来自构造函数的不同记录实例,但我不确定 TypeScript 是否会接受它。

const { Record } = require("immutable");
const uuid = require('uuid');

const tagDefaults = {
    depth: 0,
    id: undefined,
    name: "",
    order: 0,
};

class Tag extends Record(tagDefaults) {
    constructor(values) {
        super(values);

        if (this.id === undefined) {
            return this.set('id', uuid.v4());
        }

        return this;
    }
}