我已经将组件转换为使用挂钩,但是当设置状态时,我的复选框不会重新呈现。
import React, { useEffect, useState } from 'react';
import './Sorting.scss'
let fake = [
{type: 'A'},
{type: 'A'},
{type: 'A'},
{type: 'A'},
{type: 'A'},
{type: 'B'},
{type: 'B'},
{type: 'B'},
{type: 'C'},
{type: 'C'},
{type: 'C'},
]
export default function Sorting() {
const [manageableData, setManageableData] = useState([]);
useEffect(() => {
let uniqueTypes = fake.map(item => item.type).filter((value, index, self) => self.indexOf(value) === index);
let manageableData = [];
uniqueTypes.forEach(item => {
manageableData.push({ 'type' : item, 'checked': false });
});
setManageableData(manageableData)
}, []);
const handleChange = (e, index) => {
let md = manageableData;
md[index].checked = e.target.checked;
setManageableData(md)
}
const handleFiltering = () => {
let filtered = [];
manageableData.forEach(type => {
if(type.checked){
filtered.push(fake.filter(item => item.type === type.type));
}
});
console.log('Filtered Data: ', filtered.flat(filtered.length));
}
return (
<div className="checkbox-group stacked">
{manageableData.map((item, index) => (
<div className="checkbox-item" key={`${index}-checkbox-item`}>
<input
id={`${index}-checkbox`}
type="checkbox"
className="checkbox"
checked={item.checked}
onChange={(e) => handleChange(e, index, manageableData)}
/>
<label htmlFor={`${index}-checkbox`}>{item.type}</label>
</div>
))}
<div className="row">
<input
type="button"
onClick={handleFiltering}
className="btn-primary"
value="Filter"
/>
</div>
</div>
)
}
我根据状态下的manageableData重建复选框-还可以管理选中的复选框。但是,在选中其中之一后,状态会更新,但是复选框不会使用更新后的状态重新呈现。