我正在尝试访问以前的状态,但是它一直返回相同的号码,请帮助
let scrollUp = () => {
setItems(prevnumberOfItems => prevnumberOfItems + 1000);
alert(numberOfItems)
window.scrollBy(0, -numberOfItems);
alert(numberOfItems);
setCounter(counter + 1);
console.log(counter);
};
我不断在setItems和setBeforeItems中获得相同的数字
setItems(productRowLength * 530 + mobile);
setbeforeItems(prevnumberOfItems => prevnumberOfItems + 1000);
答案 0 :(得分:0)
setState
提供了回调函数,因此,如果我们执行以下操作-:
this.setState({someValue: 10});
console.log(this.state.someValue); //can't expect it to be 10, can be previous value too because setState is async.
但是,如果我们这样做--
this.setState({someValue: 10}, () => console.log(this.state.someValue)); // definitely will be 10.
setState的语法-:
this.setState({ //properties and value },//callback function to be executed);