在状态内使用解构分配

时间:2019-04-19 07:54:41

标签: reactjs eslint

class BottomPanelProgramTabs extends React.Component<Props, State> {
  state = {
    activeTab: this.props.children[0].props.label,
  };

...

ESLint希望我在其上使用解构分配

this.props.children[0].props.label

关于如何执行此操作的任何想法?

2 个答案:

答案 0 :(得分:1)

您可以这样做。 For more reference about prefer-destructuring

class BottomPanelProgramTabs extends React.Component<Props, State> {
  constructor(){
        let [props] = this.props.children;
         state = {
          activeTab : props.label
         }

   }

答案 1 :(得分:0)

 class BottomPanelProgramTabs extends React.Component<Props, State> {

  state = {
    activeTab: 'default label'
  };

  componentDidMount = () => {

    const [{ props: { label } }] = this.props.children;

    this.setState({
      activeTab: label || 'default label',
      ...
    })
  }

  ...

您可以通过使用[]获取第一个元素和使用{}获取道具来混合破坏。

例如

使用[child]将给我们数组中的第一个元素。

const children = [{
    props: {
      label: 'Some label'
    }
  },
  {
    props: {
      label: 'Second label'
    }
  },

  ,
  {
    props: {
      label: 'another label'
    }
  }]
  
  const [child] = children;
  
  console.log(child);

要获得props,我们可以继续添加[ {props} ]返回值props来混合破坏。

const children = [{
    props: {
      label: 'Some label'
    }
  },
  {
    props: {
      label: 'Second label'
    }
  },

  ,
  {
    props: {
      label: 'another label'
    }
  }]
  
  const [ {props} ] = children;
  
  console.log(props);

要从道具中获得label,就可以这样做[{ props: { label } }]

const children = [{
    props: {
      label: 'Some label'
    }
  },
  {
    props: {
      label: 'Second label'
    }
  },

  ,
  {
    props: {
      label: 'another label'
    }
  }]
  
  const [{ props: { label } }] = children;
  
  console.log(label);

具有复杂数据

const children = [{
    props: {
      label: [{
        data: {
          title: 'complex destructor'
        }
      },
      {
        data: {
          title: 'complex destructor 2'
        }
      }]
    }
  },
  {
    props: {
      label: 'Second label'
    }
  },

  ,
  {
    props: {
      label: 'another label'
    }
  }]

 const [{ props: { label: [ { data: { title } } ] } }] = children;

console.log(title)