【问题标题】:Remove from array if unchecked with React如果未使用 React 选中,则从数组中删除
【发布时间】:2016-07-21 22:31:03
【问题描述】:

选中后,添加到数组。未选中时,从数组中删除。我下面的代码有效,但 null 被放置在它的位置。我需要完全删除它。怎么样?

...

getInitialState: function(){
  return{
    email: this.props.user,
    product: []
  }
},

_product: function(){
  if (this.refs.opt1.checked) {
      var opt1 = this.refs.opt1.value;
  } else {
    this.setState({ product: this.state.product.filter(function(_, i) { return i  }) });
  };

  if (this.refs.opt2.checked) {
    var opt1 = this.refs.opt2.value;
  } else {
    this.setState({ product: this.state.product.filter(function(_, i) { return i }) });
  };
  var array = this.state.product.concat([opt1]);
  this.setState({
      product: array
  });
},

render: function(){
  return(
   <div><input ref="opt1" type="checkbox" value="foo" onClick={this._product}/></div>
  )
}

...

【问题讨论】:

  • 那个过滤功能是什么意思?删除第一个元素?另外,为什么要使用 value 而不是在复选框中选中?
  • @OriolBG 这是一种奇怪的写作方式arr.slice(1)。另外 OP,您在函数末尾调用 setState,因此之前的 setState 调用将被覆盖,更不用说如果两个选项都未选中,opt1 将未定义
  • this.setState({ product: this.state.product.filter(function(i) { return i !== null }) }); null 还在
  • 这与您的问题不同。此外,正如@azium 指出的那样,您还引入了未定义的值,而不仅仅是 null 。

标签: javascript arrays reactjs


【解决方案1】:

我认为,如果您保留一组选项,其中每个选项都有一个 selected 属性,那么管理起来会更容易。大致如下:

...
constructor(props) {
  super(props);

  this.toggleOption = this.toggleOption.bind(this);
}

getInitialState(){
  return {
    email: this.props.user,
    options: [
      { value: 'Foo1', otherProperty: 'something', checked: false },
      { value: 'Foo2', otherProperty: 'something', checked: false },
    ],
  }
}

toggleOption(index) {
  // Clone the options array
  const options = this.state.options.slice();

  // Toggle the option checked property
  if(options[index]) {
    options[index].checked = !options[index].checked;
  }

  // Update the component state
  this.setState({
    options
  });
}

getSelectedOptions() {
  // Use this to grab an array of selected options for whatever reason...
  return this.state.options.filter(option => option.checked);
}

render: function(){
  return(
    <div>
      { this.state.options.map((i, option) => {
        <input type="checkbox" checked={option.checked} value={option.value} onClick={() => this.toggleOption(i) } />
      }) }
    </div>
  )
}
...

【讨论】:

    猜你喜欢
    • 2021-01-21
    • 2020-09-26
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 2011-07-22
    • 1970-01-01
    相关资源
    最近更新 更多