本文整理汇总了TypeScript中react.useState函数的典型用法代码示例。如果您正苦于以下问题:TypeScript useState函数的具体用法?TypeScript useState怎么用?TypeScript useState使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了useState函数的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。
示例1: useState
export const useSavedState = (disabled: boolean, saved: boolean) => {
const [wasUnsaved, setWasUnsaved] = useState(false);
const [wasSaved, setWasSaved] = useState(false);
if (!saved && !wasUnsaved) setWasUnsaved(true);
if (saved && wasUnsaved && !wasSaved) setWasSaved(true);
return [disabled || saved ? true : !wasUnsaved, saved && wasSaved];
};
开发者ID:este,项目名称:este,代码行数:7,代码来源:useSavedState.ts
示例2: useState
export function useUndo<T>(initialState: T) {
const [versions, setVersions] = useState<T[]>([initialState]);
const [currentVersion, setCurrentVersion] = useState(0);
const hasUndo = currentVersion !== 0;
const hasRedo = currentVersion !== versions.length - 1;
const createVersion = (version: T) => {
const willBranch = currentVersion !== versions.length - 1;
const nextVersions = willBranch ? versions.slice(0, currentVersion + 1) : versions;
setVersions([...nextVersions, version]);
setCurrentVersion(nextVersions.length);
};
const undo = () => setCurrentVersion(Math.max(currentVersion - 1, 0));
const redo = () => setCurrentVersion(Math.min(currentVersion + 1, versions.length - 1));
return [
versions[currentVersion],
createVersion,
{
undo,
redo,
hasUndo,
hasRedo,
},
];
}
开发者ID:LWJGL,项目名称:lwjgl3-www,代码行数:31,代码来源:useUndo.ts
示例3: useState
export const useQuery = (value: string): Output => {
const [result, setResult] = useState<Result>([]);
const [loading, setLoading] = useState(false);
const [loaded, setLoaded] = useState(false);
const debounce = useRef<any>(null);
useEffect(() => {
worker.load().then(() => {
setLoaded(true);
});
}, []);
useEffect(
() => {
if (!value) return;
if (debounce.current) {
clearTimeout(debounce.current);
}
setLoading(true);
debounce.current = setTimeout(() => {
worker.solve(value).then((data: any) => {
setResult(data);
setLoading(false);
});
}, 140);
},
[value],
);
return { loaded, loading, data: result };
};
开发者ID:kerlends,项目名称:word-solver,代码行数:34,代码来源:useQuery.ts
示例4: useCanvas
export function useCanvas(
width: number,
height: number,
sourceCanvasRef?: RefObject<HTMLCanvasElement>
): [
HTMLCanvasElement | null,
CanvasRenderingContext2D | null,
(ctx: CanvasRenderingContext2D) => void
] {
const [canvas, setCanvas] = useState<HTMLCanvasElement | null>(null);
const [ctx, setCtx] = useState<CanvasRenderingContext2D | null>(null);
useEffect(() => {
const canvas = sourceCanvasRef
? sourceCanvasRef.current!
: document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d')!;
setCanvas(canvas);
setCtx(ctx);
}, []);
return [canvas, ctx, setCtx];
}
开发者ID:alcarin-org,项目名称:alcarin,代码行数:25,代码来源:CanvasUtils.ts
示例5: useState
function useAsync<Result>(fn: () => Promise<Result>) {
const [isLoading, setIsLoading] = useState(false);
const [result, setResult] = useState<Result | null>(null);
const [err, setError] = useState(null);
const isMounted = useIsMounted();
const run = useCallback(async () => {
setIsLoading(true);
try {
const res = await fn();
if (isMounted.current) {
setResult(res);
}
} catch (error) {
if (isMounted.current) {
setError(error);
}
} finally {
if (isMounted.current) {
setIsLoading(false);
}
}
}, [fn]);
return {
isLoading,
result,
error: err,
run,
};
}
开发者ID:TF2PickupNET,项目名称:TF2Pickup,代码行数:33,代码来源:use-async.ts
示例6: useApolloClient
export const useSubscription = <T, TVariables = OperationVariables>(
query: DocumentNode,
options: SubscriptionOptions<T, TVariables> = {},
): {
data: T | { [key: string]: void }
error?: GraphQLError
loading: boolean
} => {
const onSubscriptionData = options.onSubscriptionData
const prevOptions = useRef<typeof options | null>(null)
const client = useApolloClient()
const [data, setData] = useState<T | {}>({})
const [error, setError] = useState<GraphQLError | null>(null)
const [loading, setLoading] = useState<boolean>(true)
const subscriptionOptions = {
query,
variables: options.variables,
fetchPolicy: options.fetchPolicy,
}
useEffect(
() => {
prevOptions.current = subscriptionOptions
const subscription = client
.subscribe<{ data: T }, TVariables>(subscriptionOptions)
.subscribe({
next: ({ data }) => {
setData(data)
if (onSubscriptionData) {
onSubscriptionData({ client, subscriptionData: data })
}
},
error: err => {
setError(err)
setLoading(false)
},
complete: () => {
setLoading(false)
},
})
return () => {
subscription.unsubscribe()
}
},
[isEqual(prevOptions.current, subscriptionOptions) ? prevOptions.current : subscriptionOptions],
)
return useMemo(
() => ({
data,
error,
loading,
}),
[data, error, loading],
)
}
开发者ID:,项目名称:,代码行数:59,代码来源:
示例7: useEffect
const useNotifications = () => {
const [notification, setNotification] = useState<Notification>(
{} as Notification,
);
const [showNotification, setShowNotification] = useState<boolean>(false);
let timer: number = 0;
useEffect(() => {
if (!notification) return;
if (!Object.keys(notification).length) return;
setShowNotification(true);
timer = setTimeout(
() => setShowNotification(false),
NOTIFICATION_SHOW_TIME,
);
return () => {
clearTimeout(timer);
};
}, [notification]);
const hideNotification = () => {
setShowNotification(false);
clearTimeout(timer);
};
const successNotification = (
title: string,
content: string | React.ReactNode,
) => {
setNotification({
title,
content,
color: '#359c46',
icon: 'accept',
});
};
const errorNotification = (
title: string,
content: string | React.ReactNode,
) => {
setNotification({
title,
content,
color: '#359c46',
icon: 'accept',
});
};
return {
notification,
showNotification,
hideNotification,
successNotification,
errorNotification,
};
};
开发者ID:marynaKhromova,项目名称:console,代码行数:58,代码来源:Notifications.service.ts
示例8: useState
export const usePivotPreviewData = (
indexPattern: IndexPattern,
query: PivotQuery,
aggs: PivotAggsConfigDict,
groupBy: PivotGroupByConfigDict
): UsePivotPreviewDataReturnType => {
const [errorMessage, setErrorMessage] = useState('');
const [status, setStatus] = useState(PIVOT_PREVIEW_STATUS.UNUSED);
const [dataFramePreviewData, setDataFramePreviewData] = useState([]);
const aggsArr = dictionaryToArray(aggs);
const groupByArr = dictionaryToArray(groupBy);
const previewRequest = getDataFramePreviewRequest(indexPattern.title, query, groupByArr, aggsArr);
const getDataFramePreviewData = async () => {
if (aggsArr.length === 0 || groupByArr.length === 0) {
setDataFramePreviewData([]);
return;
}
setErrorMessage('');
setStatus(PIVOT_PREVIEW_STATUS.LOADING);
try {
const resp: any = await ml.dataFrame.getDataFrameTransformsPreview(previewRequest);
setDataFramePreviewData(resp.preview);
setStatus(PIVOT_PREVIEW_STATUS.LOADED);
} catch (e) {
setErrorMessage(JSON.stringify(e));
setDataFramePreviewData([]);
setStatus(PIVOT_PREVIEW_STATUS.ERROR);
}
};
useEffect(
() => {
getDataFramePreviewData();
},
[
indexPattern.title,
aggsArr.map(a => `${a.agg} ${a.field} ${a.aggName}`).join(' '),
groupByArr
.map(
g =>
`${g.agg} ${g.field} ${g.aggName} ${
isGroupByDateHistogram(g) ? g.calendar_interval : ''
} ${isGroupByHistogram(g) ? g.interval : ''}`
)
.join(' '),
JSON.stringify(query),
]
);
return { errorMessage, status, dataFramePreviewData, previewRequest };
};
开发者ID:elastic,项目名称:kibana,代码行数:55,代码来源:use_pivot_preview_data.ts
示例9: useState
export function useFirstLastSeenDomainQuery<TCache = object>(
ip: string,
domainName: string,
flowTarget: FlowTarget,
sourceId: string,
apolloClient: ApolloClient<TCache>
) {
const [loading, updateLoading] = useState(false);
const [firstSeen, updateFirstSeen] = useState(null);
const [lastSeen, updateLastSeen] = useState(null);
const [errorMessage, updateErrorMessage] = useState(null);
async function fetchDomainFirstLastSeen() {
updateLoading(true);
return apolloClient
.query<GetDomainFirstLastSeenQuery.Query, GetDomainFirstLastSeenQuery.Variables>({
query: DomainFirstLastSeenGqlQuery,
fetchPolicy: 'cache-first',
variables: {
sourceId,
ip,
domainName,
flowTarget,
defaultIndex: chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY),
},
})
.then(
result => {
updateLoading(false);
updateFirstSeen(get('data.source.DomainFirstLastSeen.firstSeen', result));
updateLastSeen(get('data.source.DomainFirstLastSeen.lastSeen', result));
updateErrorMessage(null);
return result;
},
error => {
updateLoading(false);
updateErrorMessage(error.message);
return error;
}
);
}
useEffect(() => {
try {
fetchDomainFirstLastSeen();
} catch (err) {
updateFirstSeen(null);
updateLastSeen(null);
updateErrorMessage(err.toString());
}
}, []);
return { firstSeen, lastSeen, loading, errorMessage };
}
开发者ID:,项目名称:,代码行数:54,代码来源:
注:本文中的react.useState函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论