如何在React JS的this.setState下为multi var设置相同的值

时间:2019-05-10 09:14:45

标签: javascript reactjs

我是React的新手。我想在this.setState下为multi var设置相同的值。我应该如何编写代码?

我尝试过下面的代码,但不起作用。...

isChecked_1 = isChecked_2 = isChecked_3 = isChecked_4 = isChecked_5 = isChecked_6: false,

//以下是我的代码:

export default class StudentForm extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      isChecked_1: false,   
      isChecked_2: false,   
      isChecked_3: false,   
      isChecked_4: false,   
      isChecked_5: false,   
      isChecked_6: false,   
    };
  }
  //some code here......
}

4 个答案:

答案 0 :(得分:2)

您可以使用以下代码:

export default class StudentForm extends React.PureComponent {
  constructor(props) {
    super(props);
    for (var i = 1, i <= 6, i++) {
       this.state[`isChecked_${i}`] = false;
    }
  }
  //some code here......
}

答案 1 :(得分:1)

如果重复的键清楚地表明您应该使用数组:

.py

或者只是:

  this.state = {
    isChecked: [false, false, false, false, false, false],
  };

然后您可以将其读取为 this.state = { isChecked: Array(6).fill(false), }; ,并在i处设置isChecked:

this.state.isChecked[5]

要取消设置,请在上面的行中使用 const i = 5; this.setState(({isChecked }) => ({ isChecked: isChecked.map((checked, i2) => checked || i === i2) }));

答案 2 :(得分:0)

let isChecked_1 = isChecked_2 = isChecked_3 = isChecked_4 = isChecked_5 = isChecked_6 = false
this.state = {
  isChecked_1, 
  isChecked_2,   
  isChecked_3,   
  isChecked_4,   
  isChecked_5,   
  isChecked_6,   
};

答案 3 :(得分:0)

如果您希望使用更声明式和无突变的实施方式,

const getState = length => {
  // Generate N Items, starting from 1
  const items =  Array.from({ length }, (v, k) => k + 1)
  const state = items.reduce((accumulator, i) => (
    { ...accumulator, [`isChecked_${i}`]: false }), {}
  )

  return state
} 

class StudentForm extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = getState(6);
    
    console.log(this.state);
  }
  
  render() {
    return null;
  }
}

ReactDOM.render(
  <StudentForm />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="container"></div>