gpt4 book ai didi

javascript - 状态未按预期更新

转载 作者:行者123 更新时间:2023-12-03 00:58:00 25 4
gpt4 key购买 nike

我使用按类别和文本进行过滤。在每次按文本过滤之前,我想过滤(重置)当前选择的类别。 当文本更改时,在这种情况下类别不会更新。您知道为什么会发生这种情况吗?谢谢。

    handleSearchFilter = (searchText: string) => {
const { selectedOption } = this.props;
const { currentlyDisplayed } = this.state;

this.handleSelectFilter(selectedOption);
const newDisplayed = filter(currentlyDisplayed, (symbol: any) => symbol.name.cs.includes(searchText.toLowerCase()));
this.setState({ currentlyDisplayed: newDisplayed });
};

handleSelectFilter = (selectedOption: string) => {
const { symbols } = this.props;

if (selectedOption === 'all') {
this.setState({ currentlyDisplayed: symbols });
} else {
const newDisplayed = filter(symbols, (symbol: any) => symbol.category.includes(selectedOption.toLowerCase()));
this.setState({ currentlyDisplayed: newDisplayed });
}
};

最佳答案

我认为您可以通过创建返回 newDislayed 的第三个函数来实现您想要的目的,例如:

handleSearchFilter = (searchText: string) => {
const { selectedOption } = this.props;
const newDisplayed = this.getNewDisplayed(selectedOption, searchText);
this.setState({ currentlyDisplayed: newDisplayed });
};

handleSelectFilter = (selectedOption: string) => {
const newDisplayed = this.getNewDisplayed(selectedOption);
this.setState({ currentlyDisplayed: newDisplayed });
};

getNewDisplayed = (selectedOption: string, searchText = '') => {
const { symbols } = this.props;
if (selectedOption === 'all') {
return symbols;
} else {
return filter(symbols, (symbol: any) => symbol.category.includes(selectedOption.toLowerCase()) && symbol.name.cs.includes(searchText.toLowerCase()) );
}
}

关于javascript - 状态未按预期更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52740672/

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