我正在尝试以状态数组的形式将内容添加到列表中。但是,使用我当前的代码,第一项无法正确添加自身。
InvokeAsync
当我export default class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
list: [],
total: 0.00,
...
}
}
//some unimportant code here
addToList = item => {
this.setState({list: [...this.state.list, item]});
//This method call for a method that gets the total price of all the items
this.getTotal();
}
//this method works fine, except with the first element
getTotal() {
this.setState(({sum= 0.0, items, list}) => {
items.forEach(element => {
if(this.state.list.length !== 0.0) {
if(this.state.list.includes(element.name)) {
sum += parseFloat(element.price);
}
}
});
this.setState({total: sum});
});
}
}
处于console.log
状态时,我为第一项获得了一个空数组,然后这些项延迟了一个。因此,如果我添加项目list
并查看控制台,我什么也看不到。当我添加项目A
并查看控制台时,我看到带有项目B
的{{1}}。关于什么原因的任何想法?
答案 0 :(得分:1)
请记住, setState是异步的,因此,如果您要检查更新的列表,请向setState添加回调:
addToList = item => {
this.setState( {list: [...this.state.list, item]}, () =>{
// So if you make anything here, you are sure that the state was updated successfully
console.log( this.state.list );
this.getTotal();
} );
}