简体   繁体   English

如何将用户文本输入数据存储到React Native中的对象数组中?

[英]How to store user text input data into an array of objects in react native?

does anyone know how to store user text input data into an array of objects in React Native? 有谁知道如何将用户文本输入数据存储到React Native中的对象数组中?

[
  {
    note: ‘some note’,
    created_at: 123456789
  },
  {
    note: ‘another observation note’,
    created_at: 123456789
  }
]

I'm currently just using basic Asyncstorage. 我目前仅使用基本的Asyncstorage。 I have a text input field for a user to type in notes. 我有一个文本输入字段供用户输入注释。 It currently saves it as a string in an array. 当前,它将其另存为字符串在数组中。 I want to know how to do this but with an array of objects. 我想知道如何使用对象数组来执行此操作。 Also, how would I add the created_at time stamp? 另外,如何添加created_at时间戳?

Thank you :-) 谢谢 :-)

Sounds more like a basic JavaScript question. 听起来更像是一个基本的JavaScript问题。 In the context of React, you would simply store the list of notes in the component state (or application state, if using something like Redux). 在React的上下文中,您只需将注释列表存储在组件状态(如果使用Redux之类,则为应用程序状态)。

Define an onChange event handler function for the text input and call setState with: 为文本输入定义一个onChange事件处理函数,并使用以下命令调用setState

onSomeInputChange = (text) => {
  const note = {
    note: text,
    created_at: Date.now()
  };
  this.setState({ notes: [ ...this.state.notes, note ] });
}

The above assumes you have the state variable notes that holds an array of note objects. 上面假设您具有保存一个注释对象数组的状态变量notes Using the spread operator , you can copy all the previous notes to a new array and then add the new note. 使用价差运算符 ,您可以将所有先前的音符复制到新数组中 ,然后添加新音符。 You have to do that because state is immutable and cannot be modified directly. 您必须这样做,因为状态是不可变的,不能直接修改。

Then pass that function to the onChange of your text input component: 然后将该函数传递给文本输入组件的onChange:

<TextInput ... onChange={this.onSomeInputchange} />

Other props have been omitted. 其他道具已被省略。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM