城市选择react

import React, { useEffect, useState } from 'react';
import { Cascader } from 'antd';
import { SysCityList } from '../../services/citys';

interface Option {
  value?: string | number | null;
  label: React.ReactNode;
  children?: Option[];
  isLeaf?: boolean;
  loading?: boolean;
}

const App: React.FC = () => {
  const [options, setOptions] = useState<Option[]>([]);
  useEffect(() => {
    fetchApi([0]);
  }, []);
  const fetchApi = (val: any) => {
    const type = val?.length; // 1 - 省, 2 - 市, 3 - 区
    const id = val ? val[val.length - 1] : '';
    SysCityList({ cityId: id }).then((res: any) => {
      const data = res.data.map((i: any) => {
        const obj = {
          value: i.id,
          label: i.name,
          isLeaf: false
        };
        return obj;
      });
      if (val[0] === 0) {
        // 初次调用
        setOptions(data);
      } else {
        if (type === 1) {
          setOptions((data: any) =>
            data.map((item: any) => {
              if (item.value === id) {
                return {
                  ...item,
                  children: res.data.map((i: any) => {
                    const obj = {
                      value: i.id,
                      label: i.name,
                      isLeaf: res.data.length > 0 ? false : true
                    };
                    return obj;
                  })
                };
              } else {
                return item;
              }
            })
          );
        } else if (type === 2) {
          setOptions((data) =>
            data.map((item: any) => {
              if (item.value === val[0]) {
                return {
                  ...item,
                  children: item.children.map((son: any) => {
                    if (son.value === val[1]) {
                      return {
                        ...son,
                        children: res.data.map((i: any) => {
                          const obj = {
                            value: i.id,
                            label: i.name
                          };
                          return obj;
                        })
                      };
                    } else {
                      return son;
                    }
                  })
                };
              } else {
                return item;
              }
            })
          );
        }
      }
    });
  };
  const onChange = async (value: (string | number)[], selectedOptions: Option[]) => {
    console.log(value, selectedOptions);
    fetchApi(value);
  };

  return <Cascader options={options} onChange={onChange} changeOnSelect />;
};

export default App;

  

posted @ 2023-04-10 10:51  zjxgdq  阅读(34)  评论(0编辑  收藏  举报