1

来自 react 的道具是帐户,我将它的副本保留为 previousProps,在将其设置为需要比较每个对象的状态之前,如果两个道具对象不同,则将值分配给状态。但是,之前的 props 和 redux props 都是同一种。有什么方法可以迭代它而不是在下面一一写。

static getDerivedStateFromProps(nextProps: Props, prevState: State) {
    console.log("getDerivedStateFromProps");

    Object.keys(nextProps.account).every((key) => {
    // can i compare both keys with a loop.
        if (nextProps.account.firstName !== prevState.previousProps.firstName) {
            console.log("different");
            return {
                previousProps: nextProps,
                userInfo: nextProps,
                personalInfo: {
                    first_name: nextProps.account.firstName,
                },
            };
        }
    });

    if (nextProps.account.firstName !== prevState.previousProps.firstName) {
        console.log("different");
        return {
            previousProps: nextProps,
            userInfo: nextProps,
            personalInfo: {
                first_name: nextProps.account.firstName,
            },
        };
    }

    if (nextProps.account.lastName!== prevState.previousProps.lastName) {
        console.log("different");
        return {
            previousProps: nextProps,
            userInfo: nextProps,
            personalInfo: {
                last_name: nextProps.account.lastName,
            },
        };
    }
    return null;
}
4

1 回答 1

2

我认为你可以这样做;

Object.keys(nextProps.account).every((key) => {
    if (nextProps.account[key] !== prevState.previousProps[key]) {
        return {
            previousProps: nextProps,
            userInfo: nextProps,
            personalInfo: {
                [key]: nextProps.account[key],
            },
        };
    }
});
于 2020-12-10T18:10:19.630 回答