先把兩個版本範例程式碼丟上來讓大家一起思考一下,我們明天一起來聽聽大家的答案吧!
const register = async () => {};
const Card = ({ children, onRegister }) => {
const [message, setMessage] = useState();
return (
<div>
<div>卡片標題</div>
{children}
<button
onClick={() =>
onRegister()
.then(({ data, error }) => {
if (error) {
setMessage(`註冊失敗: ${error.message}`);
} else {
setMessage("註冊成功");
}
})
.finally(() => {
setTimeout(() => setMessage(null), 3000);
})
}
>
註冊
</button>
{message && <div className="message">{message}</div>}
</div>
);
};
const Page = () => {
const handleRegister = async () => {
return register()
.then((data) => {
return { data, error: null };
})
.catch((err) => {
return { data: null, error };
});
};
return (
<div>
<Card onRegister={handleRegister}>卡片內容</Card>
</div>
);
};
const register = async () => {};
const Card = ({ children, onRegister }) => {
const [message, setMessage] = useState();
return (
<div>
<div>卡片標題</div>
{children}
<button
onClick={() =>
onRegister({
onSuccess: (member) => {
setMessage("註冊成功");
},
onError: (message) => {
setMessage(`註冊失敗: ${message}`);
},
onFinish: () => {
setTimeout(() => setMessage(null), 3000);
},
})
}
>
註冊
</button>
{message && <div className="message">{message}</div>}
</div>
);
};
const Page = () => {
const handleRegister = ({ onSuccess, onError, onFinish }) => {
register()
.then((data) => {
onSuccess(data.member);
})
.catch((err) => {
onError(data.error.message);
})
.finally(onFinish);
};
return (
<div>
<Card onRegister={handleRegister}>卡片內容</Card>
</div>
);
};