reactjs - 处理状态中的动态选择组件
问题描述
我正在尝试处理来自道具的动态 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)}
)
}
}
解决方案
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)
]
};
}
});
}
推荐阅读
- ios - 关于ios14小部件的问题——从容器app中获取动态数据
- kubernetes - 在 mount pvc 发现 ceph rook 部署问题
- python - 如何在 python 中勾勒出低对比度的对象?
- javascript - 如何找到关于 React native createStackNavigator 配置的文档
- azure - 令牌刷新到 Azure KeyVault 访问
- python - pyperclip 的奇怪行为
- android - 基于自定义属性的 buildType 的命名空间
- jquery - 如何正确使用 HTML 表格单元格内的按钮
- javascript - 按钮单击事件不会在 Codepen 中弹出
- sonarqube - STS 的 SonarLite 连接