【发布时间】: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