【发布时间】:2020-02-18 16:30:54
【问题描述】:
我有一个选择过滤器,我想按类别过滤我的产品。状态被更新但 setState 的回调没有被执行。基本上我想在状态改变时立即更新我的列表。第 31 行代码没有在 try 块中执行,它也没有捕获任何错误。
HTML
<div className="col-md-4 w-25 mt-3 ml-5">
<Select
onChange={this.handleChange}
value={selectedCategory}
placeholder="Select Category"
options={categories}
/>
</div>
JavaScript
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);
}
});
};
【问题讨论】:
-
this.setState(() => return {}, () => {callback here}) -
它正在执行,但是您的
this.state和this.setState()从错误的来源获取上下文,因为您使用的是function() {而不是() => { -
@EmileBergeron 我认为这很清楚。它看起来好像它没有执行,因为
this不是他们认为的那样,所以.filter()可能会为每个类别返回false。 -
@EmileBergeron
this可能是window和state可能恰好是他们应用程序中的全局变量?只是一个猜测。另一种可能是 rxjs 捕获了filter()中抛出的异常,并从 observable 中发出onerror消息。 -
@Muj 如果它不适合你,那么edit 你的问题与你实际尝试的代码一样 minimal reproducible example 就像 Emile 上面要求的那样,并将你的问题标记为重新打开.
标签: javascript reactjs react-native rxjs