处理处于状态的动态选择组件

时间:2019-03-20 10:52:20

标签: reactjs

我正在尝试处理来自props的动态React Select组件,并将其值设置为state并处理它们的change事件以更新状态。我的代码有效,但是我想知道这是否是updateItem函数中执行此操作的正确方法。我在下面粘贴我的组件代码。

export default class Test extends Component {
constructor(props) {
    super(props);

    this.state = {
        filters:[],
    };

    this.handleFilterUpdate = this.handleFilterUpdate.bind(this)
    this.updateItem = this.updateItem.bind(this)
}

updateItem(id, itemAttributes) {
    const index = this.state.filters.findIndex(x=> x.key === id);
    if (index === -1) {
        this.setState( {filters: [...this.state.filters, {key: id, value: itemAttributes.value}]})
    } else {
        this.setState({
            filters: [
                ...this.state.filters.slice(0, index),
                   Object.assign({}, this.state.filters[index], {key: id, value: itemAttributes.value}),
                ...this.state.filters.slice(index + 1)
            ]
        });
    }
}

handleFilterUpdate(control,obj){
    this.updateItem(control, obj)
}

renderFilters(settings, controls){
    return controls.map((control) => (

        <Select
            id={control.key}
            name={control.name}
            options={control.choices}
            clearable={false}
            onChange={this.handleFilterUpdate.bind(this, control.key)}
        />
    ));
}

render() {
    return (
            {this.renderFilters(this.state.filters, this.props.filters)}
    )
}

}

1 个答案:

答案 0 :(得分:0)

当新状态基于旧值时,最好使用setState(oldState => newState)

updateItem(id, itemAttributes) {
    this.setState(oldState => {
        const index = oldState.filters.findIndex(x=> x.key === id);
        if (index === -1) {
            return {filters: [...oldState.filters, {key: id, value: itemAttributes.value}]};
        } else {
            return {
                filters: [
                    ...oldState.filters.slice(0, index),
                       Object.assign({}, oldState.filters[index], {key: id, value: itemAttributes.value}),
                    ...oldState.filters.slice(index + 1)
                ]
            };
        }
    });
}