2017-07-20 225 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確實複製了一個副本,我沒有多想,因爲我所有的注意力都集中在道具變化上。非常感謝! –