简体   繁体   中英

Non-primitive default props in React.js?

Is it possible to specify non-primitive defaults for props in React, that are not shared across all instances?

Since the result of getDefaultProps() is cached and reused for all instances , it is not a safe place to specify non-primitive defaults.

However, components are not supposed to modify their own props , so eg setting non-primitive values on props in the constructor is a no-no. (In fact, props is immutable; React ensures this via Object.preventExtensions .)

Not sure how else to make this happen...

props are immutable. getDefaultProps is for supplying prop values to components when they aren't specified when created. props can be any valid javascript value, including nested objects, as long as they don't change .

Because props are immutable, default props are cached and shared between all instances of an object.

For things that change during the lifetime of a component, you want to use state . To specify the initial shape of your component's state, you want to use the getInitialState() function. this.props will be available in that function.

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