组件失去了先前的状态

问题描述 投票:0回答:1

我在父组件ExpandableListItem中调用子组件parentscreen.js。每当我单击可扩展列表项中的任何一项时,它都会调用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,
        })
    }
reactjs react-native expandablelistview react-component react-state
1个回答
0
投票
this.setState(prevState => ({ ...prevState, questionsListArray: c }));

[如果您想知道prevState的来源,React可以选择提供它。由于setState,请重新渲染Component,它将不保留previousState。您需要明确地传递它。希望我能帮到您!

© www.soinside.com 2019 - 2024. All rights reserved.