ahooks#useMount TypeScript Examples

The following examples show how to use ahooks#useMount. 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: root-router.tsx    From shippo with MIT License 6 votes vote down vote up
Component: React.FC<RootRouteProps> = ({ result }) => {
  const history = useNavigate()
  const location = useLocation()

  useMount(() => {
    console.log(result)
    const resource = result[0].data.resource
    localStorage.setItem('__PASSPORT', resource.passport)
    if (resource.uid > 0) {
      message.success(`已经登录,UID为${resource.uid}`)
      if (location.pathname.startsWith('/passport')) {
        history('/')
      }
    } else {
      message.error('没有登录')
      history('/passport')
    }
  })

  return (
    <Routes>
      <Route path="/passport" element={<Passport />}>
        <Route path="" element={<Page_passport />}></Route>
      </Route>
      <Route path="/dashboard" element={<Home />}>
        <Route path="" element={withLoading(lazy(() => import('~/pages/dashboard')))}></Route>
      </Route>
      <Route path="/read" element={<ReadLayout />}></Route>
      <Route path="/creation" element={<CreationLayout />}></Route>
      <Route path="*" element={<Navigate to="/dashboard" replace />}></Route>
    </Routes>
  )
}
Example #2
Source File: root-router.tsx    From shippo with MIT License 5 votes vote down vote up
Component: React.FC<RootRouteProps> = ({ result }) => {
  const history = useNavigate()
  const location = useLocation()

  useMount(() => {
    console.log(result)
    const resource = result[0].data.resource
    localStorage.setItem('__PASSPORT', resource.passport)
    if (resource.uid > 0) {
      message.success(`已经登录,UID为${resource.uid}`)
      if (location.pathname.startsWith('/passport')) {
        history('/')
      }
    } else {
      message.error('没有登录')
      history('/passport')
    }
  })

  return (
    <Routes>
      <Route path="/passport" element={<Passport />}>
        <Route path="" element={<Page_passport />}></Route>
      </Route>
      <Route path="/transform" element={<Transform />}></Route>
      <Route path="/dashboard" element={<Home />}>
        <Route path="" element={withLoading(lazy(() => import('~/pages/dashboard')))}></Route>
      </Route>
      <Route path="/users" element={<Home />}>
        <Route path="" element={withLoading(lazy(() => import('~/pages/users')))}></Route>
      </Route>
      <Route path="/temp/*" element={<Home />}>
        <Route
          path="temp_trade_20220108"
          element={withLoading(lazy(() => import('~/pages/temp/temp_trade_20220108')))}
        ></Route>
      </Route>
      <Route path="/permission/*" element={<Home />}>
        <Route
          path="role"
          element={withLoading(lazy(() => import('~/pages/permission/role')))}
        ></Route>
        <Route
          path="access"
          element={withLoading(lazy(() => import('~/pages/permission/access')))}
        ></Route>
        <Route
          path="policy"
          element={withLoading(lazy(() => import('~/pages/permission/policy')))}
        ></Route>
      </Route>
      <Route path="*" element={<Navigate to="/dashboard" replace />}></Route>
    </Routes>
  )
}
Example #3
Source File: root-router.tsx    From shippo with MIT License 5 votes vote down vote up
Component: React.FC<RootRouteProps> = ({ result }) => {
  const history = useNavigate()
  const location = useLocation()

  useMount(() => {
    console.log(result)
    const resource = result[0].data.resource
    localStorage.setItem('__PASSPORT', resource.passport)
    if (resource.uid > 0) {
      Toast.show({
        icon: 'success',
        content: `已经登录,UID为${resource.uid}`,
      })
      if (location.pathname.startsWith('/passport')) {
        history('/')
      }
    } else {
      Toast.show({
        icon: 'fail',
        content: '没有登录',
      })

      if (!location.pathname.startsWith('/temp')) {
        history('/passport')
      }
    }
  })

  return (
    <Routes>
      <Route path="/passport" element={<Passport />}>
        <Route path="" element={<Page_passport />}></Route>
      </Route>
      <Route path="/home" element={<Home />}>
        <Route path="" element={withLoading(lazy(() => import('~/pages/home')))}></Route>
      </Route>
      <Route path="/discover" element={<Home />}>
        <Route path="" element={withLoading(lazy(() => import('~/pages/discover')))}></Route>
      </Route>
      <Route path="/my" element={<Home />}>
        <Route path="" element={withLoading(lazy(() => import('~/pages/my')))}></Route>
      </Route>
      <Route path="/setting/*" element={<Setting />}>
        <Route path="" element={<Page_setting />}></Route>
      </Route>
      <Route
        path="/space/:uid"
        element={withLoading(lazy(() => import('~/layouts/space')))}
      ></Route>
      <Route path="/temp/*" element={<TempLayout />}>
        <Route
          path="temp_trade_20220108"
          element={withLoading(lazy(() => import('~/pages/temp/temp_trade_20220108')))}
        ></Route>
      </Route>
      <Route path="*" element={<Navigate to="/home" replace />}></Route>
    </Routes>
  )
}
Example #4
Source File: review.tsx    From bext with MIT License 5 votes vote down vote up
MetaReview: FC = () => {
  useMount(() => {
    trackEvent(Events.metaReview, currentMeta?.id);
  });

  const { currentMeta } = useMetaDetail();
  const theme = useTheme();

  const [reviewKey, setReviewKey] = useState('source');
  const [monaco, setMonaco] = useLocalStorageState('BEXT.DETAIL_MONACO', {
    defaultValue: false,
  });
  const history = useHistory();

  useTitle(`查看代码:${currentMeta?.name}`);

  return (
    <>
      <header
        className="px-3 flex items-center justify-between"
        style={{
          borderBottom: `1px solid ${theme.semanticColors.bodyDivider}`,
        }}
      >
        <CommandBarButton
          text="返回"
          iconProps={{ iconName: 'ChevronLeft' }}
          className="h-8 mr-2"
          onClick={() => {
            history.goBack();
          }}
        />
        <Pivot
          headersOnly
          selectedKey={reviewKey}
          onLinkClick={(item) =>
            item && setReviewKey(item.props.itemKey || 'source')
          }
          className="flex-1"
        >
          <PivotItem headerText="Source" itemKey="source" />
          <PivotItem headerText="Detail" itemKey="detail" />
        </Pivot>
        <Checkbox
          label="Monaco"
          checked={monaco}
          onChange={() => setMonaco(!monaco)}
        />
      </header>
      {monaco ? (
        <div className="flex-1 overflow-y-hidden">
          <Editor
            value={(currentMeta as any)?.[reviewKey]}
            options={{
              readOnly: true,
            }}
            language={reviewKey === 'detail' ? 'html' : 'javascript'}
          />
        </div>
      ) : (
        <div className="p-4 overflow-auto flex-1">
          <code className="whitespace-pre text-xs">
            {(currentMeta as any)?.[reviewKey]}
          </code>
        </div>
      )}
    </>
  );
}
Example #5
Source File: access.tsx    From shippo with MIT License 4 votes vote down vote up
Page_permission_access: React.FC = () => {
  const [data, setData] = useState<IPermissionAccess[]>()
  const editAccessDrawerRef = useRef<EditAccessDrawerRef>(null)

  const handleDle = useCallback((id: number) => {
    confirm({
      title: '确认删除?',
      icon: <ExclamationCircleOutlined />,
      content: '此操作不可逆',
      onOk() {
        console.log('OK')
        services.permissionAccess.del({ id }).then((hr) => {
          if (hr.data.success) {
            message.success('成功')
          } else {
            message.success('失败')
          }
        })
      },
      onCancel() {
        console.log('Cancel')
      },
    })
  }, [])

  const [columns, setColumns] = useState<ColumnsType<IPermissionAccess>>([
    {
      title: '访问规则ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '访问规则表达式',
      dataIndex: 'accessRule',
      key: 'accessRule',
    },
    {
      title: '描述',
      dataIndex: 'remark',
      key: 'remark',
    },
    {
      title: '访问规则类型',
      dataIndex: 'accessType',
      key: 'accessType',
    },
    {
      title: '被引用次数',
      dataIndex: 'permissionAssociationCount',
      key: 'permissionAssociationCount',
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            onClick={() => {
              editAccessDrawerRef.current?.open(record)
            }}
          >
            修改
          </Button>
          <Button
            type="link"
            onClick={() => {
              handleDle(record.id)
            }}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ])

  const updateTable = useCallback(async () => {
    const hr = await services.permissionAccess.find_all()
    setData(
      hr.data.resource.map((item) => {
        return { ...item, createdAt: formatTimeStr(item.createdAt) }
      })
    )
  }, [])

  useMount(() => {
    updateTable()
  })

  return (
    <div>
      <EditAccessDrawer ref={editAccessDrawerRef} onClose={() => updateTable()} />
      <Space size="middle">
        <Button type="primary" onClick={() => editAccessDrawerRef.current?.open()}>
          新增访问规则
        </Button>
      </Space>
      <Table
        rowKey="id"
        columns={columns}
        dataSource={data}
        pagination={{ position: ['bottomCenter'] }}
        size="small"
      />
    </div>
  )
}
Example #6
Source File: policy.tsx    From shippo with MIT License 4 votes vote down vote up
Page_permission_policy: React.FC = () => {
  const [data, setData] = useState<IPermissionPolicy[]>()
  const editPolicyDrawerRef = useRef<EditPolicyDrawerRef>(null)
  const editPolicyAccessDrawerRef = useRef<EditPolicyAccessDrawerRef>(null)

  const handleDle = useCallback((id: number) => {
    confirm({
      title: '确认删除?',
      icon: <ExclamationCircleOutlined />,
      content: '此操作不可逆',
      onOk() {
        console.log('OK')
        services.permissionPolicy.del({ id }).then((hr) => {
          if (hr.data.success) {
            message.success('成功')
          } else {
            message.success('失败')
          }
        })
      },
      onCancel() {
        console.log('Cancel')
      },
    })
  }, [])

  const [columns, setColumns] = useState<ColumnsType<IPermissionPolicy>>([
    {
      title: '权限策略ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '权限策略名称',
      dataIndex: 'policyName',
      key: 'policyName',
    },
    {
      title: '描述',
      dataIndex: 'remark',
      key: 'remark',
    },
    {
      title: '被引用次数',
      dataIndex: 'roleAssociationCount',
      key: 'roleAssociationCount',
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type="link" onClick={() => editPolicyDrawerRef.current?.open(record)}>
            修改
          </Button>
          <Button
            type="link"
            onClick={() => {
              handleDle(record.id)
            }}
          >
            删除
          </Button>
          <Button type="link" onClick={() => editPolicyAccessDrawerRef.current?.open(record)}>
            访问规则配置
          </Button>
        </Space>
      ),
    },
  ])

  const updateTable = useCallback(async () => {
    const hr = await services.permissionPolicy.find_all()
    setData(
      hr.data.resource.map((item) => {
        return { ...item, createdAt: formatTimeStr(item.createdAt) }
      })
    )
  }, [])

  useMount(() => {
    updateTable()
  })

  return (
    <div>
      <EditPolicyDrawer ref={editPolicyDrawerRef} onClose={() => updateTable()} />
      <EditPolicyAccessDrawer ref={editPolicyAccessDrawerRef} />
      <Space size="middle">
        <Button type="primary" onClick={() => editPolicyDrawerRef.current?.open()}>
          新增权限策略
        </Button>
      </Space>
      <Table
        rowKey="id"
        columns={columns}
        dataSource={data}
        pagination={{ position: ['bottomCenter'] }}
        size="small"
      />
    </div>
  )
}
Example #7
Source File: role.tsx    From shippo with MIT License 4 votes vote down vote up
Page_permission_role: React.FC = () => {
  const [data, setData] = useState<IRole[]>()
  const editRoleDrawerRef = useRef<EditRoleDrawerRef>(null)
  const editRolePolicyDrawerRef = useRef<EditRolePolicyDrawerRef>(null)

  const handleDle = useCallback((id: number) => {
    confirm({
      title: '确认删除?',
      icon: <ExclamationCircleOutlined />,
      content: '此操作不可逆',
      onOk() {
        console.log('OK')
        services.role.del({ id }).then((hr) => {
          if (hr.data.success) {
            message.success('成功')
          } else {
            message.success('失败')
          }
        })
      },
      onCancel() {
        console.log('Cancel')
      },
    })
  }, [])

  const [columns, setColumns] = useState<ColumnsType<IRole>>([
    {
      title: '角色ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
      key: 'roleName',
    },
    {
      title: '描述',
      dataIndex: 'remark',
      key: 'remark',
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => {
        return (
          <Space size="middle">
            <Button
              type="link"
              onClick={() => {
                editRoleDrawerRef.current?.open(record)
              }}
            >
              修改
            </Button>
            <Button
              type="link"
              onClick={() => {
                handleDle(record.id)
              }}
            >
              删除
            </Button>
            <Button
              type="link"
              onClick={() => {
                editRolePolicyDrawerRef.current?.open(record)
              }}
            >
              权限策略配置
            </Button>
          </Space>
        )
      },
    },
  ])

  const updateTable = useCallback(async () => {
    const hr = await services.role.find_all()
    setData(
      hr.data.resource.map((item) => {
        return { ...item, createdAt: formatTimeStr(item.createdAt) }
      })
    )
  }, [])

  useMount(() => {
    updateTable()
  })

  return (
    <div>
      <EditRoleDrawer ref={editRoleDrawerRef} onClose={() => updateTable()} />
      <EditRolePolicyDrawer ref={editRolePolicyDrawerRef} />
      <Space size="middle">
        <Button type="primary" onClick={() => editRoleDrawerRef.current?.open()}>
          新增角色
        </Button>
      </Space>
      <Table
        rowKey="id"
        columns={columns}
        dataSource={data}
        pagination={{ position: ['bottomCenter'] }}
        size="small"
      />
    </div>
  )
}