gpt4 book ai didi

javascript - 状态不立即更新 ReactJS

转载 作者:行者123 更新时间:2023-11-29 21:43:17 26 4
gpt4 key购买 nike

我不知道我做错了什么。我有一个事件触发一个函数来改变几个值的状态,这样我就可以触发一个 API 调用;但是,函数第一次运行时状态不会改变。第二次运行该函数时,设置了与上次运行相比的状态更改。是什么导致了这种延迟?

正如您在下面看到的那样,handleFilterChange 从事件中接收值,我可以验证这些值是否被正确接收;但是,如果我在设置后立即检查状态值,我可以看到它是未定义的。当事件第二次到来时;但是,我可以看到原来的状态变化现在已经发生,但第二个还没有。那么为什么必须调用 setState 两次才能真正设置状态?

var GridView = React.createClass({
getInitialState: function() {
window.addEventListener("scroll", this.handleScroll);
return {
data: [],
page: 0, //for pagination
loadingFlag: false,
};
},

getMainFeed: function() {

...

}, //end function
getFilteredItems: function() {
...

}, //end function
componentWillMount: function() {

},
listenForFilterChange: function() {
window.addEventListener("selectedFilterChange", this.handleFilterChange, false);
},
componentWillUnmount: function() {
window.removeEventListener("selectedFilterChange", this.handleFilterChange, false);
},
handleFilterChange: function(filter) {
//alert(filter.detail.filterType);
//Convert Data for getFilteredItems
//(EventType, Category, Buy, Inspiration) {
switch (filter.detail.filterType) {
//alert(filter.detail.filterType);
case 'category':
this.setState({
itemCategory: filter.detail.filterSelected,
});
break;
case 'event':
this.setState({
eventType: filter.detail.filterSelected,
});
break;
case 'type':
if (0){
this.setState({
filterBuy: 1,
filterInspiration: 0,
});
}
if (1){
this.setState({
filterBuy: 0,
filterInspiration: 1,
});
}
if (2){
this.setState({
filterBuy: 1,
filterInspiration: 1,
});
}
break;
case 'trending':
this.setState({
itemCategory: filter.detail.filterSelected,
});
break;
}

this.getFilteredItems();
},
componentDidMount: function() {
this.listenForFilterChange();
...
},
handleScroll:function(e){
...
},
componentDidUpdate: function() {
...
},
render: function() {
return (
<div id="feed-container-inner">
<GridMain data={this.state.data} />
</div>

);
}
});

最佳答案

setState 是异步的,因此更改不会立即反射(reflect)在状态中:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

如果您需要确认状态或根据状态变化执行逻辑,请使用描述的回调参数 here .

关于javascript - 状态不立即更新 ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31979163/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com