首页 > 解决方案 > 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)}

              />

))

标签: javascriptnode.jsreactjs

解决方案


实际上,您的状态处理逻辑没有任何问题,但是您的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
      });
    }
  }

推荐阅读