首页 > 解决方案 > 处理状态中的动态选择组件

问题描述

我正在尝试处理来自道具的动态 React Select 组件并将它们的值设置为状态并处理它们的更改事件以更新状态。我的代码有效,但我想知道这是否是函数 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)}
    )
}

}

标签: reactjs

解决方案


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)
                ]
            };
        }
    });
}

推荐阅读