javascript
const ProvinceCascader = (props) => {
const dispatch = useDispatch();
const type = props?.type || 'area';
const areaList = useSelector((state) => state.utils.areaList);
const [options, setOptions] = useState();
const [echoValue, setEchoValue] = useState();
const [statusUse, setStatusUse] = useState('echo');
useEffect(async () => {
if (Array.isArray(props.value) && statusUse == 'echo') {
// 数据回显
if (props.id && props.id.split('_')[0] !== 'serviceSites') {
//服务超市错误数据
dispatch({
type: 'utils/clearAreaList', //清空仓库缓存
});
await echoLoadData(props.value);
setEchoValue(props.value);
}
} else if (!props.value) {
// 新增时下拉
dispatch({
type: 'utils/clearAreaList', //清空仓库缓存
});
if (type == 'area' && !props.value) {
//默认成都市开始选择
loadData(531531);
} else if (type == 'nationwide' && !props.value) {
//全国开始选择
loadData(0);
}
}
}, [props.value]);
useEffect(() => {
if (areaList) {
setOptions(areaList);
}
}, [areaList]);
const onChange = (e) => {
if (e == undefined) {
setEchoValue(undefined);
}
setStatusUse('onChange');
setEchoValue(e);
loadData(e[e.length - 1]); //选中区域id
props.onChange(e);
};
const loadData = async (areaId) => {
await dispatch({
type: 'utils/getAreaList',
payload: {
parentId: areaId,
},
});
return true;
};
const echoLoadData = async (areaIds) => {
await dispatch({
type: 'utils/getEchoAreaList',
payload: areaIds,
});
return true;
};
return (
<Cascader
fieldNames={{
label: 'name',
value: 'id',
children: 'children',
}}
value={echoValue}
options={options}
onChange={onChange}
changeOnSelect
disabled={props.disabled}
allowClear
/>
);
};
export default ProvinceCascader;