我有一个简单的钩子可以帮助我处理POST请求。使用以下代码,我预计unsub
将在POST完成后成为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>
);
};
答案 0 :(得分:0)
unsub仍将是未定义的,因为尚未在挂钩中为其设置默认状态。
更改:我建议将const [unsub, setUnSub] = useState();
更改为const [unsub, setUnSub] = useState(false);
我站在一边测试,工作得很好;但是,我无法测试APIService.post。