组件失去了先前的状态

时间:2019-12-30 06:49:14

标签: reactjs react-native expandablelistview react-component react-state

我在父组件ExpandableListItem中调用子组件parentscreen.js。每当我单击可扩展列表项的任何项时,它都会调用getAnswer方法并设置状态{{ 1}}。我的担心是,每当单击子组件中的可扩展列表项的任何一项时,它总是会覆盖questionlistarray的先前状态,但是我希望先前的状态不应该被覆盖并且应该添加到新状态。

parentscreen.js

questionlistarray
<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>

2 个答案:

答案 0 :(得分:1)

您可能需要类似以下的内容:

number='a126'
oldbase=12
newbase=14

#start writing your code here
import math

def base_encode(number, base):
    # sanitize inputs
    number = str(number).lower()
    print(number)
    base = int(base)

    # legal characters
    known_digits = '0123456789abcdefghijklmnopqrstuvwxyz'
    value  = { ch:val for val,ch in enumerate(known_digits) if val<base }

    # handle negative values    
    if number[0]=='-':
        sign = -1
        number = number[1:]
    else:
        sign = 1

    # do conversion
    total = 0
    for d in number:
        try:
            total = total*base + value[d]
        except KeyError:
            if d in known_digits:
                raise ValueError("invalid digit '{0}' in base {1}".format(d, base))
            else:
                raise ValueError("value of digit {0} is unknown".format(d))

    return sign*total
def base10toN(num, base):
    """Change ``num'' to given base
    Upto base 36 is supported."""

    converted_string, modstring = "", ""
    currentnum = num
    if not 1 < base < 37:
        raise ValueError("base must be between 2 and 36")
    if not num:
        return '0'
    while currentnum:
        mod = currentnum % base
        currentnum = currentnum // base
        converted_string = chr(48 + mod + 7*(mod > 10)) + converted_string
    return converted_string
print(base10toN(base_encode(number,oldbase),newbase))

如果您想知道this.setState(prevState => ({ ...prevState, questionsListArray: c })); 的来源,React可以选择提供它。由于prevState重新呈现了Component,因此它将不保留previousState。您需要明确地传递它。希望我能帮上忙!

答案 1 :(得分:0)

getAnswer = (obj) => {
    var array = this.state.questionsListArray;

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

    this.setState({
        questionsListArray: array
    })   
}

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