为了让它发挥作用,我尝试了很多方法。
我的构造函数中有以下 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/