【问题标题】:merge to arrays into one state react-native将数组合并为一种状态 react-native
【发布时间】:2018-04-25 12:56:41
【问题描述】:

我已经尝试了很多方法来让它发挥作用。

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

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

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

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

【问题讨论】:

    标签: arrays reactjs react-native


    【解决方案1】:

    您没有确切提到您面临的问题是什么,但如果我理解正确,您在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));
        });
    }
    

    【讨论】:

    • 我的问题是dataStorage状态没有数据。在控制台日志中,它只显示空数组。 console.log('她在 state.dictionaryForAddedItems' + JSON.stringify(this.state.dataStorage));
    • @MaikenMadsen 我已经用你的代码更新了我的 asnwer。就像我说它是异步设置的。您正在设置状态一次,并依赖它完成以使用新更新再次设置它,但它还没有完成。
    • 我可以看到我的问题并没有那么清楚,因为该函数被多次调用,并且每次调用该函数时都会覆盖 dictionaryForAddedItems 中的数据。我希望将 newArray 中的数据添加到 dictionaryForAddedItems 中的现有数据中。-
    • 我在您的代码中没有看到dictionaryForAddedItems 的任何初始状态。请注意,您正在记录 this.state.dataStorage
    • 现在我明白了。我能够做到这一点: this.setState({dictionaryForAddedItems: [...this.state.dataStorage]}) 在控制台日志之前,现在它正在添加而不是覆盖。感谢您的帮助:-D
    猜你喜欢
    • 1970-01-01
    • 2019-02-06
    • 2020-09-06
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 2021-12-08
    • 2017-08-17
    相关资源
    最近更新 更多