组件
const Demo: React.FC<FormProps> = ({ visible, value, onChange }) => {
const [list, setList] = useState<any>([
{ id: 1, checked: false, },
{ id: 2, checked: false, },
{ id: 3, checked: false, },
{ id: 4, checked: false, },
{ id: 5, checked: false, },
]);
useEffect(() => {
// visible变化的时候,根据value重置checked的id值
const newList = list.map((item: any) => {
return { ...item, checked: value === item.id };
})
setList(newList);
}, [visible, list]);// 这里加上list会死循环,不加list会有lint提示
const handleItemClick = (item: any) => {
const newList = list.map((_item: any) => ({ ..._item, checked: item.id === _item.id }));
setList(newList);
onChange(item);
}
return (
<div style={{ display: 'flex' }}>
{
list.map((item: any) => <p onClick={() => handleItemClick(item)} style={{ width: 100, color: '#fff', background: item.checked ? 'red' : 'blue' }}>{item.id}</p>)
}
</div>
);
};
页面
const DemoPage: React.FC<FormProps> = () => {
const [visible, setVisible] = useState(false);
const [value, setValue] = useState(1);
const handleVisibleChange = () => {
setVisible(!visible);
if (visible) {// 每次visible为true时,重置value值
setValue(1);
}
}
const handleDemoChange = (item) => {
setValue(item.id)
}
return (
<div style={{ display: 'flex', flexDirection: 'column' }}>
<span>visible:{visible.toString()}</span>
<Button onClick={handleVisibleChange}>change visible</Button>
<Demo value={value} visible={visible} onChange={handleDemoChange} ></Demo>
</div>
);
};
useEffect加上依赖会死循环,不加依赖会有lint提示,怎么破?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…