React.js - default prop is not used with `null` is passed

非 Y 不嫁゛ 提交于 2019-12-20 16:22:58

问题


I have default props in my React component:

PropertyTitleLabel.defaultProps = {
    bedrooms: 1,
    propertyType: 'flat'
};
PropertyTitleLabel.propTypes = {
    bedrooms: PropTypes.number,
    propertyType: PropTypes.string
};

But when I'm passing null to bedrooms like:

const bedrooms = null; // in real world API returns `null`
<Component bedrooms={bedrooms} />

It's not replaced with default prop :( Any ideas?


回答1:


You can change the null value to undefined to use the default value.

<Component bedrooms={bedrooms || undefined} />



回答2:


I think there's a distinction between null and undefined that is made when dealing with the defaultProps. The null value could be intended behavior and thus isn't replaced by your defaults, while undefined is not and will be replaced.

As stated in the docs

[...] used to ensure that this.props.value will have a value if it was not specified by the parent component.

Here is a related issue.



来源:https://stackoverflow.com/questions/34809178/react-js-default-prop-is-not-used-with-null-is-passed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!