【问题标题】:Component losing the previous state组件丢失之前的状态
【发布时间】: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


【解决方案1】:

您可能需要以下内容:

this.setState(prevState => ({
      ...prevState,
      questionsListArray: c
    }));

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

【讨论】:

  • 每个项目设置单独的状态。抱歉还没有解决。
【解决方案2】:
getAnswer = (obj) => {
    var array = this.state.questionsListArray;

    for (var key in obj) {
        array.push(obj[key]);
    }

    this.setState({
        questionsListArray: array
    })   
}

您似乎正在过滤掉相应的问题,然后将另一个对象推入数组,覆盖它。我刚刚删除了过滤器。现在,它应该添加到状态中而不是覆盖任何内容。

【讨论】:

    猜你喜欢
    • 2022-12-12
    • 2020-07-29
    • 2019-01-13
    • 2020-11-26
    • 2020-10-04
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    • 2021-03-25
    相关资源
    最近更新 更多