All files / src/cascader/_example CascaderDynamicExample.jsx

10.53% Statements 2/19
0% Branches 0/6
12.5% Functions 1/8
11.11% Lines 2/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66                                1x                                                                                 1x                
import React, { useState } from "react";
import { Cascader } from "@tencent/tea-component/lib/cascader";
 
function update(data, valueList, options) {
  let current = data;
  valueList.forEach(value => {
    const option = current.options.find(option => option.value === value);
    if (option && option.child) {
      current = option.child;
    }
  });
  current.options = options;
  return { ...data };
}
 
export default function CascaderDynamicExample() {
  const [data, setData] = useState({
    title: "省份",
    options: [
      {
        label: "北京市",
        value: "bj",
        child: {
          title: "动态加载示例",
        },
      },
      {
        label: "上海市",
        value: "sh",
        child: {
          title: "动态加载示例",
        },
      },
    ],
  });
 
  function onLoad(value, options) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        // 模拟失败
        if (Math.random() > 0.7) {
          reject(new Error("Load Error"));
          return;
        }
 
        const option = options[options.length - 1];
        setData(
          update(data, value, [
            { label: `${option.label}选项一`, value: `${option.value}-1` },
            { label: `${option.label}选项二`, value: `${option.value}-2` },
          ])
        );
        resolve();
      }, 1000);
    });
  }
 
  return (
    <Cascader
      data={data}
      onChange={(value, { options }) => console.log(value, options)}
      onLoad={onLoad}
    />
  );
}