在 ReactJS 中设置缺失属性的默认值

Set default values for missing properties in ReactJS

本文关键字:属性 默认值 ReactJS 设置      更新时间:2023-09-26

假设一个组件从其父组件接收 React 中的嵌套属性:

getDefaultProps: function(){
    return ({
        "data" : {
            "style": {
                pieChart: true, // otherwise it'd be a donut chart
                radius: 100
            },
            "series": {
                "data": []
            }
        }
    });
},

可以接收具有一些缺失值的属性(例如,我们可能会收到系列但不接收样式,或者我们可能会收到半径的值,但不会收到饼图的值)

我们如何只为缺失值定义默认值? 并保留接收的其余值

您无法

getDefaultProps方法中为深层对象设置默认值,但可以在componentWillMount方法中设置默认值。

React.createClass({
  getDefaultProps() {
    return {
      "data" : {
        "style": {
          pieChart: true, // otherwise it'd be a donut chart
          radius: 100
        },
        "series": {
          "data": []
        }
      }
    }
  },
  componentWillMount() {
    if(!this.props.data.style) {
      this.props.data.style = {
        pieChart: true,
        radius: 100
      };
    }
    if(!this.props.data.series) {
      this.props.data.series = {
        data: []
      };
    }
  }
});

但是,不建议这样做,因为 React 最佳实践指出您不应从组件中修改this.props。您真正应该做的是在将对象传递到组件之前,使用 componentWillMount 中的逻辑根据自己的喜好格式化对象。

道具是要被覆盖的。您可以使用 componentWillReceiveProps 函数来处理旧 props 和新 props 之间的任何协商,但您必须自己写出逻辑。不完全确定您的数据结构是什么样子的,但我相信您可以使用下划线的_.extend_.defaults来完成这项工作。