arrays - 将数组合并到一种状态react-native

标签 arrays reactjs react-native

为了让它发挥作用,我尝试了很多方法。

我的构造函数中有以下 2 个统计数据:

constructor(props) {
super(props);
 this.state = {
   newArray: [],
   dataStorage: [],
 };
}

然后我有一个函数来处理来自 TextInput 的参数。我正在创建一个新数组来添加数据,然后我想将其添加到现有数组中。

submitHandler(inputValue, inputIdentifier) {
 console.log('inside the submitHandler');

 var newArray = [];
 newArray.push({
  value: inputValue,
  identificer: inputIdentifier.item
 });
 this.setState({newArray: newArray})

 let dataStorage = [this.state.newArray, ...this.state.dictionaryForAddedItems]

 this.setState({dataStorage: dataStorage})

  console.log('her is was inside the newArray' + JSON.stringify(newArray));
  console.log('her is was inside the state.dictionaryForAddedItems' + JSON.stringify(this.state.dataStorage));

我的日志是这样的: Log in debug looks like this

最佳答案

您没有准确提及您面临的问题是什么,但如果我理解正确,您在 console.log 中看不到更新的状态。

如果是这种情况,您应该知道 setState 是异步的。
您可以使用 setState 的第二个参数,它是一个回调函数。

setState({myKey:myVal}, () => {console.log(this.state.myKey)})

这是代码的固定版本(您也可以调用 setState 一次,使用 2 个键而不是两次调用):

submitHandler(inputValue, inputIdentifier) {
    console.log('inside the submitHandler');

    var newArray = [];
    newArray.push({
        value: inputValue,
        identificer: inputIdentifier.item
    });
    this.setState({ newArray: newArray })

    let dataStorage = [newArray, ...this.state.dictionaryForAddedItems]

    this.setState({ dataStorage: dataStorage }, () => {

        console.log('her is was inside the newArray' + JSON.stringify(newArray));
        console.log('her is was inside the state.dictionaryForAddedItems' + JSON.stringify(this.state.dataStorage));
    });
}

关于arrays - 将数组合并到一种状态react-native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47254234/

相关文章:

reactjs - React - Redux 表单在表单重置后未验证

react-native - 在 React-Native/Expo 移动应用程序上设置 Detox 时出错 : "ReferenceError: element is not defined"

javascript - 测试套件无法运行 TypeError : Cannot read property 'bind' of undefined

Ruby:如何将变量设置为 0,或者如果已经设置,则递增 1

mysql - 在 MySQL 中使用 JSON 数组

javascript - 如何从基于对象数组内部的对象数组返回值的总和

javascript - 取消之前的 promise

ruby-on-rails - 如何改进用 `' ` 引用所有数组元素并返回包含所有这些引用和逗号分隔元素的字符串的代码?

javascript - 使用 Materialize 添加自定义样式以响应元素

css - 是否可以从外部覆盖现有样式化的组件样式?