const withUsePosition = (Component: React.ComponentType<Props>) => {
return (props: Props) => {
const position = usePosition()
return <Component {...props} position={position} />
}
}
class UsePosition extends React.Component<Props & { position: Position }> {
render() {
return this.props.children(this.props.position)
}
}
export default withUsePosition(UsePosition)
import { useState, useEffect } from 'react';
type RequestStatus = 'idle' | 'loading' | 'success' | 'error';
interface RequestState<T> {
status: RequestStatus;
data: T | null;
error: Error | null;
}
type RequestFunction<T> = () => Promise<T>;
function useRequest<T>(requestFn: RequestFunction<T>): RequestState<T> {
const [status, setStatus] = useState<RequestStatus>('idle');
const [data, setData] = useState<T | null>(null);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
const fetchData = async () => {
try {
setStatus('loading');
const response = await requestFn();
setData(response);
setStatus('success');
} catch (err) {
setError(err);
setStatus('error');
}
};
fetchData();
}, [requestFn]);
return { status, data, error };
}
export default useRequest;
import React, { useState, useCallback } from "react";
const Counter = () => {
const [count, setCount] = useState(0);
const handleIncrement = useCallback(() => {
setCount(count + 1);
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={handleIncrement}>Increment</button>
</div>
);
};
// 登录页面
function login() {
// 保存用户信息到 Cookie 中
document.cookie = username={username}; expires={time}; path=/;
}
// 主页
function init() {
// 从 Cookie 中获取用户信息
const username = getCookie('username');
if (username) {
// 自动登录
showDashboard(username);
} else {
// 显示登录页面
showLogin();
}
}
// 从 Cookie 中获取指定名称的值
function getCookie(name) {
const cookie = document.cookie.split('; ');
for (let i = 0; i < cookie.length; i++) {
const [key, value] = cookie[i].split('=');
if (key === name) {
return decodeURIComponent(value);
}
}
return null;
}