我有一个简单的钩子来帮助我处理POST请求。使用以下代码,我希望在 POST 完成后unsub
true
。谁能指出我可能做错了什么?
定制挂钩
const useUnsubscribeEmail = () => {
const [userId, setUserId] = useState(null);
const [unsub, setUnSub] = useState();
const UNSUB_URL = '/web-registry-api/v1/reviews/unsubscription';
useEffect(() => {
if (userId) {
// async POST call
(async () => {
try {
await ApiService.post(`${UNSUB_URL}/${userId}`);
// update unsub value
setUnSub(true);
} catch (error) {
console.error(error)
}
})();
}
}, [userId]);
return [unsub, setUserId];
};
export default useUnsubscribeEmail;
元件
const ReviewUnsubscription = () => {
const { userId } = useParams();
const [unsub, unsubscribeEmail] = useUnsubscribeEmail();
return (
<MinimumLayout>
<div className={styles.content}>
<h1>Unsubscribe from email reminders to review products you’ve received from Zola?{unsub}</h1>
{/* unsub here is still undefined */}
<Button disabled={unsub} onClick={() => { unsubscribeEmail(userId); }} variant="primary" className={styles.button}>Unsubscribe</Button>
</div>
</MinimumLayout>
);
};
在您单击该按钮之前,unsub 仍然是未定义的,因为您尚未在钩子中为其设置默认状态。 更改:const [unsub, setUnSub] = useState();
到const [unsub, setUnSub] = useState(false);
是我推荐的
我这边测试了一下,工作得很好;但是,我无法测试 APIService.post。