在React中转换状态数组会返回undefined作为第一项

时间:2017-07-13 16:58:23

标签: javascript reactjs

我有一个复选框列表,选中它们时会通过setState添加到数组中。我想将此数组转换为单个可读字符串,该字符串应在状态更改时更改,然后将其传递给子组件。复选框以年龄为特色,所以例如我的状态设置为[7,8,9,10]我希望字符串输出为' 7,8,9,10'。

我遇到的问题是,第一次点击复选框时(例如,值为&#39; 7&#39;)的<?php //$cost = $this->input->post('cost'); //$price = $this->input->post('price'); //Suppose I have added dummy values in these variable as you received from view. $cost = array(1,2,3); $price = array(3,4,1); //as you mentioned each one cost have price like $cost zero index compared with $price zero index. $i = 0; foreach($cost as $cos){ if ($price[$i] > $cos) { echo "Rejected"; } else { echo "Accepted"; } $i++; } ?> 将返回&#39; undefined 7&#39 ;尽管readableSelectedCheckboxes返回为&#39; [7]&#39;。

这是我处理状态的父组件。

selectedCheckboxes

触发addCheckboxToList函数的子组件应该通过props接收字符串(为了简洁起见,减去一些变量)。

export default class InputWithTooltip extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedCheckboxes: [],
      readableSelectedCheckboxes: '',
    };
  }

  addCheckboxToList = (e) => {
    const clickedCheckbox = e.target.value;
    if (this.state.selectedCheckboxes.includes(clickedCheckbox)) {
      const filteredArray = this.state.selectedCheckboxes.filter(item => item !== clickedCheckbox);
      this.setState({ selectedCheckboxes: filteredArray }, () => {
        this.readableSelectedCheckboxes();
      });
    } else {
      this.setState({ selectedCheckboxes: this.state.selectedCheckboxes.concat(clickedCheckbox) }, () => {
        this.readableSelectedCheckboxes();
      });
    }
  };

  readableSelectedCheckboxes = () => {
    const selectedCheckboxes = this.state.selectedCheckboxes;
    let readableSelectedCheckboxes;

    for (let i = 0; i < selectedCheckboxes.length; i++) {
      readableSelectedCheckboxes += ` ${selectedCheckboxes[i].toString()}`;
      if (i !== selectedCheckboxes.length - 1) {
        readableSelectedCheckboxes += ',';
      }
    }
    this.setState({ readableSelectedCheckboxes });
  }

  render() {
    return (
      <CheckboxInput
        handleCheckboxChange={e => this.addCheckboxToList(e)}
        readableSelectedCheckboxes={this.state.readableSelectedCheckboxes}
        options={this.props.options}
      />
    );
  }
}

0 个答案:

没有答案