2017-07-20 127 views
0

我正在处理一个包含多个子组件的组件,这些组件可以被选中(或“激活”,因为这里的命名是这样说的。)。我有一组ID应该初始化,所有ID都被选中,所以this.state.activeSensors指的是传感器总数列表:this.props.mainViewSensors。 函数sensorSelect获取ID,并且应该由此能够确定它是否被选择。我的方法是检查它是否在activeSensors列表中 - 如果它存在,请将其删除,如果不存在,请将其添加。设置新的状态。React setState更新道具

当我从新列表newActiveSensors中移除一个物品并调用setState时,被点击的物品也会以某种方式从道具上消失。我不知道这是可能的。这是我做错了什么吗?

这里是我做过什么:

const propTypes = { 
    mainViewSensors: PropTypes.arrayOf(PropTypes.string), 
}; 

const defaultProps = { 
    mainViewSensors: [ 
     '21EL', 
     '05LO', 
     '08HT', 
     '81EL', 
     '05TF', 
    ], 
} 

class Multiselect extends React.Component { 
    constructor(props) { 
     super(props); 
     this.sensorSelect = this.sensorSelect.bind(this); 
     this.state = { 
      activeSensors: this.props.mainViewSensors, 
      selectedSensors: this.props.mainViewSensors, 
     }; 
    } 

    sensorSelect(sensor) { 
    const newActiveSensors = this.state.activeSensors; 
    if (newActiveSensors.includes(sensor)) { 
     const index = newActiveSensors.indexOf(sensor); 
     newActiveSensors.splice(index, 1); 
    } else { 
     newActiveSensors.push(sensor); 
    } 
    this.setState({ 
     activeSensors: newActiveSensors, 
    }); 
    } 

    render() { 
    const { selectedSensors, activeSensors } = this.state; 

    return (
    <div className="wrapper"> 
     {this.state.selectedSensors.map((tag) => (
      <div key={tag} role="button" className="main-gauge-holder" onClick={this.sensorSelect(tag)}> 
       <MainGauge tag={tag} /> 
      </div> 
     ))} 
    </div> 
    ); 
    } 
} 

Multiselect.propTypes = propTypes; 
Multiselect.defaultProps = defaultProps; 

React.render(<Multiselect />, document.getElementById('container')); 

只是要清楚,我正在做这样的事情,在这一个选择(这里的绿色箭头显示我已经手动更改活动状态子组件):

回答

1

这其实不是一个做出反应的问题,您刚刚使用阵列的同一个实例在你的类。您必须登录make a new array才能使用它的副本。

见我的例子中澄清:

var primaryArray = [1, 2, 3]; 
 

 
console.log('Init :'); 
 
console.log(primaryArray); 
 

 
var obj = { 
 
    array: primaryArray, // Same instance 
 
    clonedArray: primaryArray.slice() // Clone 
 
}; 
 

 
console.log(obj); 
 

 
console.log('Poping from the same instance :'); 
 
obj.array.pop(); 
 

 
console.log(obj); 
 
console.log(primaryArray); 
 

 
console.log('Poping from the cloned array doesn\'t affect primary one :'); 
 
obj.clonedArray.pop(); 
 

 
console.log(obj); 
 
console.log(primaryArray);

+0

哦,我,这个工作就像一个魅力!我认为功能开始时的const确实复制了一个副本,我没有多想,因为我所有的注意力都集中在道具变化上。非常感谢! –