1. 手撕:React实现Rate
import axios from "axios";
import { useEffect, useState, type Dispatch, type SetStateAction } from "react";
const Rate = (props: { readonly max?: number; readonly readonly?: boolean; readonly setReadonly?: Dispatch<SetStateAction<boolean>>; }) => {
const { max = 5, readonly = false, setReadonly = () => { } } = props;
const [starArr, setStarArr] = useState(new Array(max).fill(false));
return <>
<div>
{starArr.map((star, index) => {
return <span
onClick={
() => {
if (readonly) {
return;
}
const newStarArr = starArr.map((_star, ind) => {
return ind <= index ? true : false;
});
setStarArr(newStarArr);
axios.post('/submitStar', { data: newStarArr }).then(e => e.data).then((res) => {
setStarArr(res);
setReadonly(true);
}).catch((e) => {
console.error('error', e);
setStarArr(starArr);
});
}
}
>
{star ? '亮' : '暗'}
</span>;
})}
</div>
</>;
};
const max = 5;
const ShowOrder = (props: { readonly title: string; }) => {
const { title } = props;
const [readonly, setReadonly] = useState(false);
const [isShowRate, setIsShowRate] = useState(false);
const [starArr, setStarArr] = useState(new Array(max).fill(false));
useEffect(() => {
axios.get('/queryStar').then((res) => {
setReadonly(res.data);
setStarArr(starArr);
});
}, []);
return <div
onMouseEnter={() => {
setIsShowRate(true);
}}
onMouseLeave={() => {
setIsShowRate(false);
}}
>
<h1
>{title}</h1>
{isShowRate ? <Rate
readonly={readonly}
setReadonly={setReadonly}
starArr={starArr}
max={5}
/> : null}
</div>;
};
2. 算法
async function request(url, options) {
const {timeout = 1000, ...restOptions} = options
const rsp = await fetch(url, restOptions)
return rsp
}
request('http://127.0.0.1:1337', {timeout: 1})
.then(console.log)
.catch(console.error)
async function newRequest (url: string, options: { readonly timeout?: number; }) {
const { timeout = 1000, ...restOptions } = options;
return Promise.race([
() => fetch(url, restOptions),
() => new Promise((_resolve, reject) => {
setTimeout(reject, timeout);
}),
]);
}