umi#useRequest TypeScript Examples

The following examples show how to use umi#useRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.tsx    From umi-micro-apps with MIT License 6 votes vote down vote up
UserList = (props: any) => {
  const { shopId } = props;
  const { data = [] } = useRequest(() => request(`/api/user/list?shopId=${shopId}`));

  const columns = [
    {
      dataIndex: 'id',
      title: 'ID',
    },
    {
      dataIndex: 'name',
      title: '姓名',
    },
    {
      dataIndex: 'address',
      title: '住址',
    },
    {
      dataIndex: 'id',
      title: '操作',
      render: (id: string) => (
        <Link to={`/${id}`}>详情</Link>
      )
    },
  ];

  return (
    <div>
      <h1 style={{ marginBottom: 24 }}>用户列表</h1>

      <Table rowKey="id" columns={columns} dataSource={data} />

    </div>
  );
}
Example #2
Source File: index.tsx    From ant-design-pro-V4 with MIT License 4 votes vote down vote up
DashboardWorkplace: FC = () => {
  const { loading: projectLoading, data: projectNotice = [] } = useRequest(queryProjectNotice);
  const { loading: activitiesLoading, data: activities = [] } = useRequest(queryActivities);
  const { data } = useRequest(fakeChartData);

  const renderActivities = (item: ActivitiesType) => {
    const events = item.template.split(/@\{([^{}]*)\}/gi).map((key) => {
      if (item[key]) {
        return (
          <a href={item[key].link} key={item[key].name}>
            {item[key].name}
          </a>
        );
      }
      return key;
    });
    return (
      <List.Item key={item.id}>
        <List.Item.Meta
          avatar={<Avatar src={item.user.avatar} />}
          title={
            <span>
              <a className={styles.username}>{item.user.name}</a>
              &nbsp;
              <span className={styles.event}>{events}</span>
            </span>
          }
          description={
            <span className={styles.datetime} title={item.updatedAt}>
              {moment(item.updatedAt).fromNow()}
            </span>
          }
        />
      </List.Item>
    );
  };

  return (
    <PageContainer
      content={
        <PageHeaderContent
          currentUser={{
            avatar: 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png',
            name: '吴彦祖',
            userid: '00000001',
            email: '[email protected]',
            signature: '海纳百川,有容乃大',
            title: '交互专家',
            group: '蚂蚁金服-某某某事业群-某某平台部-某某技术部-UED',
          }}
        />
      }
      extraContent={<ExtraContent />}
    >
      <Row gutter={24}>
        <Col xl={16} lg={24} md={24} sm={24} xs={24}>
          <Card
            className={styles.projectList}
            style={{ marginBottom: 24 }}
            title="进行中的项目"
            bordered={false}
            extra={<Link to="/">全部项目</Link>}
            loading={projectLoading}
            bodyStyle={{ padding: 0 }}
          >
            {projectNotice.map((item) => (
              <Card.Grid className={styles.projectGrid} key={item.id}>
                <Card bodyStyle={{ padding: 0 }} bordered={false}>
                  <Card.Meta
                    title={
                      <div className={styles.cardTitle}>
                        <Avatar size="small" src={item.logo} />
                        <Link to={item.href}>{item.title}</Link>
                      </div>
                    }
                    description={item.description}
                  />
                  <div className={styles.projectItemContent}>
                    <Link to={item.memberLink}>{item.member || ''}</Link>
                    {item.updatedAt && (
                      <span className={styles.datetime} title={item.updatedAt}>
                        {moment(item.updatedAt).fromNow()}
                      </span>
                    )}
                  </div>
                </Card>
              </Card.Grid>
            ))}
          </Card>
          <Card
            bodyStyle={{ padding: 0 }}
            bordered={false}
            className={styles.activeCard}
            title="动态"
            loading={activitiesLoading}
          >
            <List<ActivitiesType>
              loading={activitiesLoading}
              renderItem={(item) => renderActivities(item)}
              dataSource={activities}
              className={styles.activitiesList}
              size="large"
            />
          </Card>
        </Col>
        <Col xl={8} lg={24} md={24} sm={24} xs={24}>
          <Card
            style={{ marginBottom: 24 }}
            title="快速开始 / 便捷导航"
            bordered={false}
            bodyStyle={{ padding: 0 }}
          >
            <EditableLinkGroup onAdd={() => {}} links={links} linkElement={Link} />
          </Card>
          <Card
            style={{ marginBottom: 24 }}
            bordered={false}
            title="XX 指数"
            loading={data?.radarData?.length === 0}
          >
            <div className={styles.chart}>
              <Radar
                height={343}
                data={data?.radarData || []}
                angleField="label"
                seriesField="name"
                radiusField="value"
                area={{
                  visible: false,
                }}
                point={{
                  visible: true,
                }}
                legend={{
                  position: 'bottom-center',
                }}
              />
            </div>
          </Card>
          <Card
            bodyStyle={{ paddingTop: 12, paddingBottom: 12 }}
            bordered={false}
            title="团队"
            loading={projectLoading}
          >
            <div className={styles.members}>
              <Row gutter={48}>
                {projectNotice.map((item) => (
                  <Col span={12} key={`members-item-${item.id}`}>
                    <Link to={item.href}>
                      <Avatar src={item.logo} size="small" />
                      <span className={styles.member}>{item.member}</span>
                    </Link>
                  </Col>
                ))}
              </Row>
            </div>
          </Card>
        </Col>
      </Row>
    </PageContainer>
  );
}
Example #3
Source File: index.tsx    From scorpio-h5-design with MIT License 4 votes vote down vote up
export default function() {
  const { pageId, pageSchema, selectPage, setStateByObjectKeys } = useModel('bridge');
  const addPageReq = useRequest(service.addPage, {
    manual: true,
  });
  const editPageReq = useRequest(service.editPage, {
    manual: true,
  });
  const [visible, { toggle }] = useBoolean(false);
  const [qrcodeUrl, setQrcodeUrl] = useState('');

  const save = async function() {
    const dataURL = await window.postmate_mobile.get(childrenModel.CAPTURE);
    if (dataURL) {
      const file = dataURLtoFile(dataURL, new Date().getTime().toString());
      const fileName = `${uuidv4()}.png`;
      await ossClient.put(`design/${fileName}`, file);
      selectPage.cover = `https://scorpio-design.lxzyl.cn/design/${fileName}`;
    }
    let res;
    if (pageId) {
      res = await editPageReq.run({
        _id: pageId,
        pageSchema,
      });
    } else {
      res = await addPageReq.run({
        pageSchema,
      });
    }
    return res;
  };

  const onSave = async function() {
    if (pageSchema.length === 0) {
      return message.error('请新建页面后再保存!');
    }
    if (selectPage.components.length === 0) {
      return message.error('至少添加一个组件后再保存!');
    }
    const res = await save();
    const state = {
      pageId: res._id,
    };
    setStateByObjectKeys(state);
    message.success('保存成功!');
  };

  const onVisibleChange = async function() {
    if (pageSchema.length === 0) {
      return message.error('请新建页面后再操作!');
    }
    toggle();
    await save();
    const dataUrl = await QRCode.toDataURL(`${config.h5Base}?id=${pageId}`, {
      margin: 0,
    });
    console.log('dataUrl: ', dataUrl);
    setQrcodeUrl(dataUrl);
  };

  const overviewContent = (
    <div className="overview-qrcode">
      <img className="overview-qrcode-img" src={qrcodeUrl} />
    </div>
  );

  const exportJson = function() {
    const blob = new Blob([JSON.stringify(pageSchema)], { type: 'application/json' });
    console.log('pageSchema: ', pageSchema);
    FileSaver.saveAs(blob, `${pageSchema[0].props.title}.json`);
  };

  return (
    <div className="design-header">
      <div className="design-header-operations">
        <div className="item" onClick={() => { history.push('/manage/page'); }}>
          <i className="iconfont icon-shouye" />
          <div className="text" >首页</div>
        </div>
        <div className="item" onClick={onSave}>
          <i className="iconfont icon-baocun" />
          <div className="text" >保存</div>
          <Spin spinning={addPageReq.loading || editPageReq.loading}>
          </Spin>
        </div>
        {/* <Popover
          title="真机预览"
          trigger="click"
          visible={visible}
          onVisibleChange={onVisibleChange}
          content={overviewContent}
          overlayClassName="overview-qrcode-popover"
        >

          <div className="item">
            <i className="iconfont icon-shouji" />
            <div className="text">预览</div>
          </div>
        </Popover> */}
        <div className="item" onClick={exportJson}>
          <i className="iconfont icon-json" />
          <div className="text">导出</div>
        </div>
        {/* <div className="item">
          <i className="iconfont icon-html" />
          <div className="text">下载</div>
          <i className="iconfont icon-new" style={{position: 'absolute', color: 'red', right: 0, top: 0}}/>
        </div> */}
        <div className="item" onClick={() => { window.open('https://github.com/lx544690189/scorpio-h5-design'); }}>
          <i className="iconfont icon-github-fill" />
          <div className="text">GITHUB</div>
        </div>
      </div>
    </div>
  );
}
Example #4
Source File: index.tsx    From scorpio-h5-design with MIT License 4 votes vote down vote up
export default function() {
  // @ts-expect-error
  const { _id } = history.location.query;
  const { setStateByObjectKeys } = useModel('bridge');
  const queryPageDetailReq = useRequest(service.queryPageDetail, {
    manual: true,
  });
  const [loading, setLoading] = useBoolean(true);

  useEffect(() => {
    initData();
    return ()=>{
      window.postmate_mobile.destroy();
    };
  }, []);

  /**
   * 初始化数据、编辑页面初始数据
   */
  const initData = async function() {
    setLoading.setTrue();
    // 加载iframe、发送请求、更新state会导致页面短时间卡顿,延时进行这些任务
    await sleep(100);
    let state = {
      pageId: undefined,
      pageSchema: [],
      selectPageIndex: -1,
      selectComponentId: undefined,
    };
    if (_id) {
      const res = await queryPageDetailReq.run({
        _id,
      });
      state = {
        pageId: res._id,
        pageSchema: res.pageSchema,
        selectPageIndex: 0,
        selectComponentId: undefined,
      };
    }
    setStateByObjectKeys(state, false);
    await sleep(100);
    const handshake = new Postmate({
      container: document.getElementById('mobile-content'),
      url: `${config.base}/#/mobile`,
      name: 'mobile',
      classListArray: ['mobile'],
    });
    handshake.then((child) => {
      window.postmate_mobile = child;
      syncState({
        payload: state,
        type: IMessageType.syncState,
      });
      // 注册事件
      child.on(childrenModel.SYNC_STATE, (message) => {
        setStateByObjectKeys(message, false);
      });
      setLoading.setFalse();
    });
  };

  return (
    <Spin
      spinning={useDebounce(loading, { wait: 500 })}
      wrapperClassName="blur-loading"
      indicator={<Loading />}
    >
      <div className="design">
        <Header />
        <div className="side-left">
          {!loading && <SideLeft />}
        </div>
        <div className="side-right">
          {!loading && <SideRight />}
        </div>
        <div className="center">
          <MobileSimulator loading={loading}/>
        </div>
      </div>
    </Spin>
  );
}
Example #5
Source File: index.tsx    From scorpio-h5-design with MIT License 4 votes vote down vote up
export default function() {
  const [form] = Form.useForm();
  const [edit, setEdit] = useState<{
    visible: boolean,
    data: Record<string, unknown>,
    type: 'add' | 'edit' | 'detail',
  }>({
    visible: false,
    data: {},
    type: 'add',
  });
  const { tableProps, search, refresh } = useAntdTable(service.getCategoryList, {
    form,
    defaultParams: [
      { current: 1, pageSize: 10 },
      {
        sort: { createdAt: -1 },
      },
    ],
    formatResult(res) {
      res.data.list.forEach((item: any) => delete item.children);
      return res.data;
    },
  });
  const addCategoryReq = useRequest(service.addCategory, {
    manual: true,
  });
  const editCategoryReq = useRequest(service.editCategory, {
    manual: true,
  });
  const deleteCategoryReq = useRequest(service.deleteCategory, {
    manual: true,
  });
  const { submit, reset } = search;

  const add = function() {
    setEdit({
      visible: true,
      data: {},
      type: 'add',
    });
  };
  const cancel = function() {
    setEdit({
      visible: false,
      data: {},
      type: 'add',
    });
  };
  const confirm = async function(values: any) {
    if (edit.type === 'add') {
      await addCategoryReq.run(values);
    }
    if (edit.type === 'edit') {
      await editCategoryReq.run({
        _id: edit.data._id as string,
        name: values.name,
      });
    }
    setEdit({
      visible: false,
      data: {},
      type: 'add',
    });
    await refresh();
  };
  const onEdit = function(data: any) {
    setEdit({
      visible: true,
      data,
      type: 'edit',
    });
  };
  const onDelelte = async function(data: any) {
    await deleteCategoryReq.run({
      _id: data._id,
    });
    setEdit({
      visible: false,
      data: {},
      type: 'add',
    });
    await refresh();
  };
  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '操作',
      width: 180,
      render(data: any) {
        return (
          <Space split={<Divider type="vertical" />}>
            <Typography.Link onClick={() => { onEdit(data); }}>修改</Typography.Link>
            <Popconfirm
              title="确认此操作?"
              onConfirm={() => { onDelelte(data); }}
              okText="确认"
              cancelText="取消"
            >
              <Typography.Link type="danger">删除</Typography.Link>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];
  const SearchForm = (
    <div>
      <Form form={form}>
        <Row gutter={24}>
          <Col span={8}>
            <Form.Item label="分类名称" name="name">
              <Input placeholder="name" />
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Form.Item style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <Button type="primary" onClick={submit}>
              查询
            </Button>
            <Button onClick={reset} style={{ marginLeft: 16 }}>
              重置
            </Button>
          </Form.Item>
        </Row>
      </Form>
    </div>
  );
  return (
    <PageHeader
      className="manage-category"
      ghost={false}
      onBack={() => null}
      title="组件分类管理"
      extra={[
        <Button key="1" type="primary" onClick={add}>
          新增
        </Button>,
      ]}
    >
      {SearchForm}
      <Table columns={columns} rowKey="_id" {...tableProps} />
      <FormRenderDrawer
        type={edit.type}
        visible={edit.visible}
        onCancel={cancel}
        formSchema={formSchema}
        onSubmit={confirm}
        loading={addCategoryReq.loading}
        formData={edit.data}
      />
    </PageHeader>
  );
}
Example #6
Source File: index.tsx    From scorpio-h5-design with MIT License 4 votes vote down vote up
Component = function() {
  const { queryAllWithComponent } = Model.useContainer();
  const [componentDraw, setComponentDraw] = useState({
    category: {},
    component: {},
    visible: false,
    data: {},
  });
  const addComponentReq = useRequest(service.addComponent, {
    manual: true,
  });
  const editComponentReq = useRequest(service.editComponent, {
    manual: true,
  });
  const deleteComponentReq = useRequest(service.deleteComponent, {
    manual: true,
  });

  const edit = function({ _id }: any) {
    history.push(`/manage/component/detail?componentId=${_id}`);
  };

  const onCancel = function() {
    setComponentDraw({
      category: {},
      component: {},
      visible: false,
      data: {},
    });
  };
  const onSubmit = async function(values: any) {
    // @ts-expect-error
    if(!componentDraw.component._id){
      await addComponentReq.run({
        // @ts-expect-error
        categoryId: componentDraw.category._id,
        ...values,
      });
    }else{
      await editComponentReq.run({
        // @ts-expect-error
        _id: componentDraw.component._id,
        ...values,
      });
    }
    setComponentDraw({
      category: {},
      component: {},
      visible: false,
      data: {},
    });
    await queryAllWithComponent.refresh();
  };
  const onAddComponent = function(category: any) {
    setComponentDraw({
      category,
      component: {},
      visible: true,
      data: {},
    });
  };

  const copyId = function(component: any) {
    //
  };

  const dev = async function(component: any) {
    // @ts-expect-error
    if(!h5Lib[component._id]){
      return message.error('组件不存在,请检查本地h5lib目录');
    }
    history.push(`/manage/component/detail?componentId=${component._id}`);
  };

  const onEditComponent = function(component: any, category: any){
    setComponentDraw({
      category,
      visible: true,
      data: {...component},
      component,
    });
  };

  const onDeleteComponent = function(component: any) {
    confirm({
      title: '确认删除此组件?',
      icon: <ExclamationCircleOutlined />,
      content: '请确保组件未被其他页面引用',
      okText: '确认',
      okType: 'danger',
      cancelText: '取消',
      onOk: async()=> {
        await deleteComponentReq.run({
          _id: component._id,
        });
        await queryAllWithComponent.refresh();
      },
    });
  };

  return (
    <PageHeader
      className="manage-component"
      ghost={false}
      onBack={() => null}
      title="组件开发"
      subTitle="开发流程:申请组件ID->h5Lib目录下新增组件->组件开发页面编辑、测试"
    >
      <Spin spinning={queryAllWithComponent.loading}>
        <Tabs tabPosition='left'>
          {
            queryAllWithComponent.data.map((category: any) => (
              <TabPane tab={<>{category.name}<Badge count={category.components.length} /></>} key={category._id}>
                <Button
                  type="dashed"
                  block
                  className="manage-component-add-btn"
                  icon={<PlusOutlined />}
                  onClick={() => onAddComponent(category)}
                >新增</Button>
                {
                  category.components.map((component: any) => (
                    <Card
                      key={component._id}
                      className="manage-component-card"
                      // cover={
                      //   component.cover ? <img
                      //     alt="example"
                      //     src={component.cover}
                      //   /> : <Empty description={false} />
                      // }
                      actions={[
                        <Tooltip title={`ID:${component._id}`} key="id">
                          <Typography.Link onClick={() => copyId(component)}>ID</Typography.Link>
                        </Tooltip>,
                        <Typography.Link key="edit" onClick={() => dev(component)}>组件开发</Typography.Link>,
                        <Dropdown
                          key="more"
                          trigger={['click']}
                          overlay={
                            <Menu>
                              <Menu.Item key="0" onClick={() => { onEditComponent(component, category); }}>
                                编辑
                              </Menu.Item>
                              <Menu.Item key="1" onClick={() => { onDeleteComponent(component); }}>删除</Menu.Item>
                            </Menu>
                          }
                        >
                          <a className="ant-dropdown-link" onClick={(e) => e.preventDefault()}>
                            更多 <DownOutlined />
                          </a>
                        </Dropdown>,
                      ]}
                    >
                      <div className="manage-component-card-img">
                        <img src={component.cover} />
                      </div>
                      <Paragraph ellipsis={{ rows: 2, expandable: true, symbol: 'more' }}>
                        {component.name}
                      </Paragraph>
                    </Card>
                  ))
                }
              </TabPane>
            ))
          }
        </Tabs>
      </Spin>
      <FormRenderDrawer
        type="add"
        visible={componentDraw.visible}
        onCancel={onCancel}
        formSchema={formSchema}
        onSubmit={onSubmit}
        loading={addComponentReq.loading}
        formData={componentDraw.data}
      />
    </PageHeader>
  );
}
Example #7
Source File: index.tsx    From scorpio-h5-design with MIT License 4 votes vote down vote up
export default function() {
  const [qrcodeUrl, setQrcodeUrl] = useState('');
  const queryPageListReq = useRequest(service.queryPageList);
  const togglePageTemplateReq = useRequest(service.togglePageTemplate, {
    manual: true,
  });

  const onAddPage = function() {
    history.push('/design');
  };

  const onEditPage = function(item:any){
    history.push({
      pathname: '/design',
      query: {
        _id: item._id,
      },
    });
  };

  const onMouseEnter = async function(pageId:string) {
    setQrcodeUrl('');
    const dataUrl = await QRCode.toDataURL(`${config.h5Base}?id=${pageId}`, {
      margin: 2,
    });
    setQrcodeUrl(dataUrl);
  };

  const toggleTemplate = async function(item:any) {
    await togglePageTemplateReq.run({
      _id: item._id,
      isTemplate: !item.isTemplate,
    });
    message.info('操作成功!');
    queryPageListReq.refresh();
  };

  const downloadHtml = function(item:any){
    //
  };


  return (
    <PageHeader
      className="manage-page"
      ghost={false}
      title="页面搭建"
      extra={[
        <Button key="1" type="primary" onClick={onAddPage}>
          创建新页面
        </Button>,
      ]}
    >
      <Spin spinning={queryPageListReq.loading}>
        <div className="manage-page-container">
          {
            queryPageListReq.data&&  queryPageListReq.data.list.map((item:any)=>(
              <div className="manage-page-item" key={item._id}>
                <Card
                  className="page-card"
                  cover={
                    <div className="page-card-main">
                      <img
                        className="page-card-img"
                        alt="example"
                        src={item.pageSchema[0]?.cover}
                      />
                      <div
                        className="page-card-pop"
                        onMouseEnter={()=>{onMouseEnter(item._id);}}
                      >
                        <img className="page-card-pop-qrcode" src={qrcodeUrl}/>
                        <Button className="page-card-pop-btn" type="dashed" size="small" onClick={()=>{onEditPage(item);}}>编辑</Button>
                        <Button className="page-card-pop-btn" type="dashed" size="small" onClick={()=>{toggleTemplate(item);}}>{item.isTemplate ? '取消模板' : '设为模板'}</Button>
                        <Button className="page-card-pop-btn" type="dashed" size="small" onClick={()=>{downloadHtml(item);}}>
                          下载到本地
                        </Button>
                      </div>
                    </div>
                  }
                >
                  <div className="title">{item.pageSchema[0].props.title}</div>
                  <div className="time">
                    <span className="version">V1.0</span>
                    {moment(item.createdAt).format('YYYY-MM-DD HH:mm:ss')}
                  </div>
                </Card>
              </div>
            ))
          }
        </div>
        {/* <div className="manage-page-pagination">
          <Pagination defaultCurrent={1} total={50} />
        </div> */}
      </Spin>
    </PageHeader>
  );
}