简体   繁体   中英

React & Typescript: nested defaultProps deep merge

I'm creating a React & Typescript component and need to define some default props which are objects with nested data. Here is a simplified example of my component:

type Props = {
    someProp: string,
    user: {
        blocked: boolean,
        active: boolean
    }
}

export const UserPage: React.FC<Props> = props => {
    (...)
};

Then I define default props like so:

const defaultProps: Props = { 
    user: {
        blocked: true
    }
}

UserPage.defaultProps = defaultProps

The problem is, if my component is called with the following props

<UserPage user={{ active: true }}/>

than the user object in the default props will be overwritten completely.

What is the best way to declare and merge props and default props with nested data?

You can use

const propsWithDefaults = Object.assign(defaultProps, props);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM