【发布时间】:2019-12-30 06:49:14
【问题描述】:
我在父组件parentscreen.js 中调用子组件ExpandableListItem。每当我点击任何可扩展列表项时,它都会调用getAnswer 方法并设置状态questionlistarray。我担心的是无论何时单击子组件中可扩展列表项的任何项,它总是覆盖 questionlistarray 的先前状态,但我希望先前的状态不应该覆盖并且应该添加到新状态。
parentscreen.js
<View style={{ height: this.state.layout_Height, overflow: 'hidden' }}> {
this.props.item.sub_Category.map((item, key) => (
<View style={styles.sub_Category_Text}>
<Text style={{ fontWeight: 'bold' }}> {item.sub_name} </Text>
{
item.name.map((item1, key) => (
<View>
<Text style={{ marginTop: 10 }}> {item1.question} </Text>
<ExpandableListItem
quesId={item1.question_id}
assignedToList={ this.props.assignedToList}
setAnswer={this.getAnswer} />
{/* {this.renderQuestions(item1.question_id, this.props.assignedToList)} */} </View>
))
} </View>
))
} </View>
getAnswer = (obj) => {
var array = this.state.questionsListArray;
// AsyncStorage.getItem('qArray').then((value) => {
// if (value != null) {
// //this.setState({ questionsListArray: value })
// // console.log(value)
// array = value;
// } else {
// array = this.state.questionsListArray
// }
// })
for (var key in obj) {
var c = array.filter((item) => item.question_id != key)
c.push(obj[key]);
}
c.map((item, key) => (
console.log("array is " + " " + item.question_id + " " + item.Answer + " " + item.comment + " " + item.assignedTo + " ")
))
// AsyncStorage.setItem('qArray',JSON.stringify(c));
this.setState({
questionsListArray: c,
})
}
【问题讨论】:
-
'@anshulsinha' 我认为你应该不可变地更新你的状态。您正在做的是,您正在尝试可变地更新 questionsListArray ,因此覆盖数组中以前存在的任何内容,而不是首先尝试克隆您以前的状态,然后将某些内容推送到您的数组中。希望对你有帮助!!
标签: reactjs react-native expandablelistview react-component react-state