javascript - react js中动态生成的切换(开关)不起作用
问题描述
我的项目中有两种开关状态。一个是默认的,另一个是从 API 生成的。更改项目时,切换开关将不起作用。
constructor(props) {
super(props);
this.state = {
switch_status: [true, false],
items: [{title:toyota}, {title:bmw}]
}
}
有一个函数,它从 API 获取数据并设置为项目:
changeItems = () => {
this.setState({ items: [{title:toyota, switch_status: true},
{title:porche, switch_status: true},
{title:bmw, switch_status: false}]
});
}
开/关不起作用,当项目更改时:
//Switch on/off function
handleChange = (event, id) => {
const isChecked = event;
this.setState(
({switch_status}) => ({
switch_status: {
...switch_status,
[id]: isChecked,
}
})
);
}
//Loop Items
this.state.items.map((item, index) => (
<Switch
className="custom-switch custom-switch-primary"
checked={this.state.switch_status[index]}
id={index}
onChange={event => handleChange(event, index)}
/>
))
解决方案
实际上,您的状态处理逻辑没有任何问题,但是您的componentDidUpdate()被无限次调用,因为内部检查不起作用,即使您不需要,它也会覆盖您的切换状态。
将您的componentDidUpdate()更改为:
componentDidUpdate(previousProps, previousState) {
if (
JSON.stringify(previousProps.mediaTypes.items) !==
JSON.stringify(this.props.mediaTypes.items)
) {
this.dataListRender();
this.setState({
customMediaTypesItems: this.props.mediaTypes.items.custom_media_types
});
}
}
推荐阅读
- oracle11g - 如何在 Apache Nifi 中读取仅重复一次的数据?
- spring-boot - 在 Fargete ECS 集群中引用 Docker 容器的环境变量
- mips - 如何将 jr $ra 直接放到正确的位置?
- python - 在 MAC 上安装 anaconda 后无法使用 conda
- ssl - 自签名 https gitlab
- reactjs - 使用 React 在页面上滚动可见
- java - 在java中使用函数式风格有什么好处?
- java - 休眠两级级联不适用于显式清除 Set
- python - 如何在遍历python中的列表时标记编码
- java - ms word的图像在我打开后10秒后消失