gpt4 book ai didi

javascript - 在购物车应用程序中选择项目后, react 动态搜索栏不更新列表

转载 作者:行者123 更新时间:2023-11-30 19:55:14 24 4
gpt4 key购买 nike

我正在尝试编写一个购物车应用程序,当我们在搜索栏中输入一个值时,它应该更新列表并根据输入的值显示可用的项目。使用我编写的代码,一切正常,直到我选择了一个没有在第一次更新 View 并显示所有 channel 的项目。(我认为状态不是第一次更新,而是第二次更新)

我对 react 很陌生。我试图在这里只添加必要的代码来解决问题。

state = { open: false, value: '', filteredSections: 'none', displaySections: [] };

filterFunction(e, someSections) {
const filteredSections = [];
this.setState({ value: e.target.value });
someSections.forEach((category) => {
const results = [];
const itemCopy = {...category};
category.arraysinside.forEach((item) => {
if (item.name.toLowerCase().includes(e.target.value.toLowerCase())) { results.push(item); }
});
itemCopy.arraysinside = results;
if (itemCopy.arraysinside.length > 0) { filteredSections.push(itemCopy); }
});
this.setState({ filteredSections: filteredSections });
return filteredSections;
}
updateFunction(displaySections) {
this.setState({ displaySections: displaySections });
}
onChange(opt) {
// makes item selected and changes color of item to know that item is selected
}
render() {
const someSections = customization.arraysinside.filter(c => c.has === 'channels');
let { displaySections, filteredSections } = this.state;
return (
<div>
<FormControl
name="search-items"
placeholder="Search items"
onChange={(e) => {
filteredSections = this.filterFunction(e, someSections);
this.setState({
displaySections: filteredSections.length > 0 ? displaySections = filteredSections : 'No',
value: this.state.value,
});
}}
/>
<div>
{displaySections.length > 0 ? displaySections.map(section =>
<someSections
onChange={(opt) => {
onChange(opt);
this.updateFunction(opt, displaySections);
}}
:
someSections.map(section =>
<someSections
onChange={opt => onChange(opt)}
/>)
}
</div>
</div>
);
}
}

JSON 格式将是

{
"name": "product 1",
"has": "channels",
"arraysinside": [
{ "selected": false, "name": "Item 1"},
{ "selected": false, "name": "Item 2"},
{ "selected": false, "name": "Item 3"},
{ "selected": false, "name": "Item 4"},
],
},
{
"name": "product 2",
"has": "channels",
"arraysinside": [
{ "selected": false, "name": "Item 1"},
{ "selected": false, "name": "Item 2"},
{ "selected": false, "name": "Item 3"},
{ "selected": false, "name": "Item 4"},
],
},

displaySections 应该在我每次选择项目时更新,并且应该立即更改 View ,但是使用当前代码,它会在我输入另一个值或下次更新选择时更新。请帮忙,我已经尝试了好几天了,但没有任何改善。如果建议比我写的更简单的方法,我会很高兴。

最佳答案

setState() 是异步的,所以试试:

this.setState({ value: e.target.value }, () => { ... do stuff replying on value });

关于javascript - 在购物车应用程序中选择项目后, react 动态搜索栏不更新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54066819/

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