在ReactNative中推送到状态数组

时间:2020-10-30 23:42:22

标签: javascript react-native state

我在我的代码中向以下事件分配一个onPress事件(请注意注释):

export default class App extends React.Component {
state = {
  noteArray: [],
  noteText: "",
};
constructor(props: any) {
  super(props);
}
addNote() {
  if (this.state.noteText) {
    var d = new Date();
    let noteArray = [...this.state.noteArray];
    noteArray.push({
    date: d.getFullYear() + "/" + d.getMonth() + "/" + d.getDate(),
        note: this.state.noteText,
      });
    //If I place a "console.log(noteArray); return;" here I get the object I expect.
    this.setState({ noteArray });
    //If I set the same "console.log" here I will get an empty array in console (because the "valuated just now" but if I do console.log(noteArray[0]) I get the correct object)
      return true;
    }
  }
}

我无法修改变量“ this.state.noteArray”。如果最后使用console.log变量,那么我总是以空数组结尾。这是调用它的对象:

        <TouchableOpacity
          style={styles.addButton}
          onPress={this.addNote.bind(this)}
        >
          <Text style={styles.addButotnText}>+</Text>
        </TouchableOpacity>

我还有另一个修改状态的对象,但这可以成功完成此操作:

     <TextInput
        style={styles.textInput}
        placeholderTextColor="white"
        underlineColorAndroid="transparent"
        placeholder=">Note"
        value={this.state.noteText}
        onChangeText={(noteText) => this.setState({ noteText })}
      ></TextInput>

感谢您的亲切见解

1 个答案:

答案 0 :(得分:-3)

我认为这可能是因为您没有以正确的方式使用setState, 你应该做:

this.setState({ noteArray: noteArray })

而不是:

this.setState({ noteArray });

希望我能帮助您;)