1.创建变量
const [loading, setLoading] = useState<boolean>(false);
const [error, setError] = useState<string>()
2.useEffect钩子控制变量值的变化
useEffect(() => {
const fetchData = async () => {
setLoading(true);
try {
const responses = await fetch(
"https://jsonplaceholder.typicode.com/users"
);
// .then(response => response.json())
// .then(data => setRobotGallery(data))
const data = await responses.json();
setRobotGallery(data);
} catch (e:any) {
setError(e.message);
}
setLoading(false);
};
fetchData();
}, []);
ps:注意useEffect()方法中第二个参数使用[],避免请求陷入死循环。参考:https://reactjs.org/docs/hooks-reference.html#useeffect
3.使用变量控制html元素的渲染
return (
<div className={styles.app}>
<div className={styles.appHeader}>
<img src={logo} className={styles.appLogo} alt="logo" />
<h1>罗伯特机器人炫酷吊炸天online购物平台的名字要长</h1>
</div>
<button
onClick={() => {
setCount(count + 1);
}}
>
Click
</button>
<span>count: {count}</span>
<ShoppingCart />
{(!error || error !== "") && <div>网站出错:{error}</div>}
{!loading ? (
<div className={styles.robotList}>
{/* r必须要有类型定义,此处暂时定义为any */}
{robotGallery.map((r:any) => (
<Robot id={r.id} email={r.email} name={r.name} />
))}
</div>
) : (
<h2>loading 加载中</h2>
)}
</div>
);