【问题标题】:How to remove unchecked checkbox from React state array?如何从 React 状态数组中删除未选中的复选框?
【发布时间】:2021-01-21 12:15:24
【问题描述】:

使用复选框 onChange 事件,如何在未选中时从状态数组中删除值?

状态数组:

this.state = { value: [] }

onChange函数:

handleChange = event => {
    if (event.target.checked) {
        this.setState({
            value: [...this.state.value, event.target.value]
        });
    } else {
        this.setState({
            value: [this.state.value.filter(element => element !== event.target.value)]
        });
    }
};

不确定 .filter() 应该做什么

【问题讨论】:

    标签: javascript arrays reactjs onchange


    【解决方案1】:

    非常接近,除了:

    1. 您需要删除调用filter 周围的[]filter 返回一个数组。如果您将其包装在 [] 中,您会将数组放入另一个数组中,而这是您不想要的(在这种情况下)。

    2. 由于您是根据现有状态更新状态,因此使用setState 的回调版本很重要,而不是直接接受对象的版本。状态更新可以一起批处理,因此您需要确保处理的是最新版本的数组。

    所以:

    handleChange = ({target: {checked, value: checkValue}}) => {
    //             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    //                 ^− destructuring to take the properties from the event,
    //                    since the event object will get reused and we're doing
    //                    something asynchronous below
        if (checked) {
            this.setState(({value}) => ({value: [...value, checkValue]}));
        } else {
            this.setState(({value}) => ({value: value.filter(e => e !== checkValue)}));
            //                                  ^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^−−− No [] around  this
        }
    };
    

    在某些情况下,您可以使用 this.state.value 而不是使用回调(例如,如果您更新 value 以响应某些事件),但您必须确保您知道它们是哪些;使用回调更简单。


    FWIW,因为它有多个值,如果是我,我会调用状态属性 values(复数)而不是 value,这也意味着我们不必重命名 @987654331 @来自上面解构中的事件目标:

    handleChange = ({target: {checked, value}}) => {
        if (checked) {
            this.setState(({values}) => ({values: [...values, value]}));
        } else {
            this.setState(({values}) => ({values: values.filter(e => e !== value)}));
        }
    };
    

    【讨论】:

    • 嘿@T.J.克劳德,谢谢你的回答:) 你认为元素 !== event.target.value 也可以吗?
    • @js-learner - 是的,因为您直接存储复选框的值,所以您正在比较同类。请注意更新,您可能还想在上面做第二件事。
    • 啊,太棒了,完全有道理,非常感谢:)
    • this.setState(({values}) => ({values: checked ? [...values, value] : values.filter(e => e !== value)}));
    • @DennisVash - 在 OP 的原始文件中是 value,这是第一个代码块相关的内容;只有 values 在最后一个代码块中建议更改状态属性的名称。
    猜你喜欢
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多