【问题标题】:How to compare two objects value by iterating if both have same name in getDerivedStateFromProps?如果 getDerivedStateFromProps 中两个对象的名称相同,如何通过迭代来比较两个对象的值?
【发布时间】:2023-04-11 06:04:02
【问题描述】:

来自 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;
}

【问题讨论】:

    标签: reactjs typescript react-native redux getderivedstatefromprops


    【解决方案1】:

    我认为你可以这样做;

    Object.keys(nextProps.account).every((key) => {
        if (nextProps.account[key] !== prevState.previousProps[key]) {
            return {
                previousProps: nextProps,
                userInfo: nextProps,
                personalInfo: {
                    [key]: nextProps.account[key],
                },
            };
        }
    });
    

    【讨论】:

    • 这很聪明,我对反应完全陌生,这似乎是一个好方法。
    猜你喜欢
    • 2019-05-29
    • 2023-03-31
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2014-09-23
    • 2013-12-20
    相关资源
    最近更新 更多