我们正在尝试根据项目是否被选中对清单进行排序。如果选中某个项目,则会将其移动到列表的底部。
项目的索引成功更新(因此,一旦检查了第一项,它将移至底部,索引将更改为1而不是0,而以前为索引1的项目现在为索引1)。
但是,如果我们点击索引为1的项目,则由于某种原因(而不是未选中索引1的项目)检查索引为0的项目。
我们尝试过一些东西,但不知道造成这种情况的原因,所以任何想法都会有所帮助。
谢谢!
const database = {
"Design Checklist" : {
"icon" : "ti-help",
"items" : [ {
"badExamplePicture" : "https://res.cloudinary.com/ootje/image/upload/v1474832696/DSC01717_ctd4k0.jpg",
"checked" : false,
"collapsed" : true,
"desc" : "Desc.",
"goodExamplePicture" : "https://res.cloudinary.com/ootje/image/upload/v1474832696/DSC01717_ctd4k0.jpg",
"itemName" : "Item",
"labels" : [ "Colors", "Layout" ],
"quickWin" : 1
}, {
"badExamplePicture" : "https://res.cloudinary.com/ootje/image/upload/v1474832696/DSC01717_ctd4k0.jpg",
"checked" : false,
"collapsed" : true,
"desc" : "Description.",
"goodExamplePicture" : "https://res.cloudinary.com/ootje/image/upload/v1474832696/DSC01717_ctd4k0.jpg",
"itemName" : "Someitem",
"labels" : [ "Layout" ],
"quickWin" : 2
} ],
"name" : "Design Checklist"
}
};
class Checklists2 extends React.Component {
state = {
allChecklists: null,
selectedChecklist: "Design Checklist",
searchTerm: ""
};
componentWillMount = () => {
this.setState({ allChecklists: database});
};
check = indexOfModifiedItem => {
const isChecked = this.state.allChecklists[this.state.selectedChecklist]
.items[indexOfModifiedItem].checked;
this.setState({
allChecklists: update(this.state.allChecklists, {
[this.state.selectedChecklist]: {
items: { [indexOfModifiedItem]: { checked: { $set: !isChecked } } }
}
})
});
};
collapse = indexOfModifiedItem => {
const isCollapsed = this.state.allChecklists[this.state.selectedChecklist]
.items[indexOfModifiedItem].collapsed;
this.setState({
allChecklists: update(this.state.allChecklists, {
[this.state.selectedChecklist]: {
items: {
[indexOfModifiedItem]: { collapsed: { $set: !isCollapsed } }
}
}
})
});
};
searchItems = () => {
this.setState({ searchTerm: this.search.value });
};
render() {
return (
<div>
{this.state.allChecklists[this.state.selectedChecklist].items.filter(item => {
if (item.itemName.includes(this.state.searchTerm))
return true;
return false;
})
.sort((item,item2) => {
if(item.checked) return 1
else return 0
})
.map((item, i) => {
return (
<ChecklistItem
key={item.itemName}
indexOfItem={i}
checklistItem={item}
toggleCheck={this.check}
toggleCollapse={this.collapse}
/>
);
})}
</div>
)}
}
class ChecklistItem extends React.Component {
render() {
return (
<div>
<li>{this.props.checklistItem.itemName}</li>
<button onClick={() => this.props.toggleCheck(this.props.indexOfItem)}>Click me</button>
</div>
);
}
}
ReactDOM.render(<Checklists2/>, document.getElementById("root"));
<div id="root"></div>