如何使用传播算子更新React JS中的状态?

时间:2019-03-29 14:31:18

标签: reactjs setstate

我需要按类别过滤问题列表,因此我决定在复选框更改时在空表类别中添加category_id,但表格仍为空?

//国家的定义

constructor(props) {
    super(props);
    this.handleCategoryChange.bind(this)
    this.state = {
        filters: []
    }
}

//复选框类别更改

handleCategoryChange (category, e) {
    if (e.target.checked) {
        this.setState((state) => ({
            filters: [[...state.filters], ...[category.id]]
        }));
        console.log(this.state.filters) // empty
    }
}

//复选框输入

render() {
    return (

        <div className="form-check mb-2">
            <input className="form-check-input" type="checkbox" id={'category-'  + this.props.category.id} onChange={(e) => this.handleCategoryChange(this.props.category, e)}/>
            <label className="form-check-label" htmlFor="category">
                { this.props.category.name }
            </label>
        </div>
    )
}

2 个答案:

答案 0 :(得分:1)

首先... setState()是异步操作,因此console.log(this.state.filters)可以为空,也可以不为空。请尝试以下代码。您应该在选中/取消选中类别后对其进行调试,以使其正常工作。

 handleCategoryChange (category, e) {

        if (e.target.checked) {
             const filters = [...this.state.filters,
                   category.id
             ]
            this.setState({
                filters: filters
            });
            console.log(this.state.filters) // empty
        } else {
               //....
         }
    }

答案 1 :(得分:0)

handleCategoryChange (category, e) {
    if (e.target.checked) {
        this.setState((state) => ({
            filters: [...state.filters, ...category.id]
        }), (newState) => console.log(newState.filters));
    } else {
        const newFilters = [...state.filters];
        newFilters.splice(category.id, 1);
        this.setState((state) => {
            const newFilters = [...state.filters];
            newFilters.splice(category.id, 1);
            return {
                filters: [...state.filters, ...category.id]
            }
        }
    }
}