【问题标题】:Update an element in an array object at state by using textInput React Native使用 textInput React Native 更新数组对象中处于状态的元素
【发布时间】:2017-12-28 22:44:06
【问题描述】:

我在这里尝试做的是使用 textInput 更新数组对象“可用”,下面是我的代码。我不知道为什么它一直在 _update 函数行给我令牌错误。请帮忙。谢谢!

export class Inventory extends Component {
state = {
    available: [
        {id: 0, name: 'Xb', value:5},
        {id: 1, name: 'Ad', value:19},
        {id: 2, name: 'Sc', value:1},
        {id: 3, name: 'AV', value:3},
        {id: 4, name: 'Ba', value:8},
        {id: 5, name: 'Ch', value:2},
        {id: 6, name: 'Pr', value:9},
        {id: 7, name: 'Mi', value:10},
        {id: 8, name: 'Se', value:1},
    ],
}

    _update = (text,index) => this.setState({available[index].value: text});

render(){
 index = 0;
  return(
    <View style={styles.container}> 
      <TextInput style={styles.input}
      keyboardType = 'number-pad'
      returnKeyType = 'go' 
      autoCapitalize = 'none'
      maxLength = {3}
      value = {this.state.available[index].value}
      onChange = {(text) => _update(text,index)} />
    </View>
  );
}

【问题讨论】:

    标签: react-native textinput


    【解决方案1】:

    _update = (text,index) =&gt; this.setState({available[index].value: text}); 在某些方面无效。首先,setState 获取一个对象,如果您要更新值,该对象应该与您现在的状态中的键和值相同。其次,available[index].value 不会计算为任何值,因为未定义 available。您只能通过this.state.available 访问available。第三,available[index].value 将成为新组件状态的关键,我认为这不是您想要的。

    把你的更新改成这样

    _update = (text, index) => {
      const newArray = [...this.state.available];
      newArray[index].value = text;
      this.setState({ available: newArray });
    }
    

    【讨论】:

    • 感谢您的回复。 ...[...this.state.available] 是什么?
    • 也就是所谓的展开算子。检查此developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 以供参考。基本上,对于数组,展开运算符获取数组中的项目并将它们放入我们正在创建的新数组中。
    • 我正在尝试相同的方法,但它说 无法在写入事务之外修改托管对象。 ...我正在处理本机和领域数据库以填充该数组.
    • 尝试按照领域文档并将用于填充数组的代码包装在“realm.write(() => {...})”块中
    【解决方案2】:

    永远不要像使用普通的 javascript 方式那样直接改变 this.state。实际上你应该记住 this.state 是不可变的。最好的办法:

    1- 首先创建状态数组的副本。

    2- 查找项目的索引(如果索引可用,则跳过此项)。

    3- 更新该索引处项目的值。

    4- 使用 setState 更新状态值。 因此,在您的情况下,您会执行以下操作:

     (text,index) => {
       let newArray = [...this.state.available];
         newArray[index] = {...newArray[index], value: text}
       this.setState({available: newArray});
      }
    

    希望对你有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-21
      • 2019-01-16
      • 2021-04-07
      • 1970-01-01
      • 1970-01-01
      • 2019-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多