Javascript setState不执行回调
我有一个选择过滤器,我想按类别过滤我的产品。状态已更新,但setState的回调未执行。基本上,当状态改变时,我想立即更新我的列表。代码行31不会在try blok中执行,它也不会捕获任何错误 HTML 将此行更改为:this.setState{selectedCategory:event.value},函数{更改为this.setState{selectedCategory:event.value},=>{Javascript setState不执行回调,javascript,reactjs,react-native,rxjs,Javascript,Reactjs,React Native,Rxjs,我有一个选择过滤器,我想按类别过滤我的产品。状态已更新,但setState的回调未执行。基本上,当状态改变时,我想立即更新我的列表。代码行31不会在try blok中执行,它也不会捕获任何错误 HTML 将此行更改为:this.setState{selectedCategory:event.value},函数{更改为this.setState{selectedCategory:event.value},=>{ 调用它“function”会改变这个上下文。这段代码成功了,但仍然不知道它为什么不起作
调用它“function”会改变这个上下文。这段代码成功了,但仍然不知道它为什么不起作用。有人能解释一下吗 handleChange=事件=>{
this.setState(
{ selectedCategory: event.value },
this.showFilteredProducts
);
};
showFilteredProducts() {
const filterItems = products.pipe(
map(products =>
products.filter(
product => product.category === this.state.selectedCategory
)
)
);
filterItems.subscribe(products => {
this.setState({
items: products,
isLoaded: true
});
});
}
this.setState=>返回{},=>{callback here}它正在执行,但是您的this.state和this.setState从错误的源获取上下文,因为您使用了函数{而不是=>{@EmileBergeron我认为这很清楚。它似乎没有执行,因为这不是他们认为的,所以.filter可能会为每个类别返回false。@EmileBergeron这可能是窗口,状态可能恰好是他们应用程序中的全局变量?只是猜测。另一种可能是rxjs捕捉到了异常ion被抛出过滤器,并从可观察对象发出一条onerror消息。@Muj如果它对你不起作用,那么你的问题和你实际尝试过的代码就像Emile上面要求的那样,并标记你的问题重新打开。这是一个经常重复的问题。我已经尝试过你的解决方案,但没有运气。我忘了删除该函数在发布之前。在调试过程中,它从code product.pipe oprator跳转,DOM也不会重新登录。您是否尝试过包装产品。pipe…调用try catch以查看是否出错?
handleChange = event => {
console.log(event.value);
this.setState({ selectedCategory: event.value }, () => {
try {
products.pipe(
map(products =>
products
.filter(
product => product.category === this.state.selectedCategory
)
.subscribe(products => {
console.log(products);
this.setState({
items: products,
isLoaded: true
});
})
)
);
} catch (error) {
console.error(error);
}
});
};
handleChange = event => {
console.log(event.value);
this.setState({ selectedCategory: event.value }, () => { // this line right here
products.pipe(
map(products =>
products
.filter(product => product.category === this.state.selectedCategory)
.subscribe(products => {
console.log(products);
this.setState({
items: products,
isLoaded: true
});
})
)
);
});
};
this.setState(
{ selectedCategory: event.value },
this.showFilteredProducts
);
};
showFilteredProducts() {
const filterItems = products.pipe(
map(products =>
products.filter(
product => product.category === this.state.selectedCategory
)
)
);
filterItems.subscribe(products => {
this.setState({
items: products,
isLoaded: true
});
});
}