javascript - 按钮组件需要两次点击
问题描述
我的网站上有一个发货表单部分,最后有一个按钮,它应该获取表单的值并将这些数据发布到我的后端服务器,但是每当我第一次单击时没有任何效果,它只能工作在第二次点击时。
这是我的自定义按钮组件
function Button(props) {
return (
<div className={props.className}>
<Link to={props.buttonLink}>
<button
className={`${styles.buttonDefault} ${
props.display ? '' : styles.hideButton
} ${props.buttonClass}`}
onClick={props.onClick}
>
{props.buttonText}
</button>
</Link>
</div>
);
}
export default Button;
这是我在另一个 jsx 文件中使用的按钮组件
<Button
buttonClass={styles.buttonClass}
buttonText="CONFIRM ORDER"
onClick={onClickShippingButton}
display
/>
这是我的按钮组件触发的代码
const onClickShippingButton = () => {
setButtonClicked(true);
// Set validated to true
if (firstName && lastName && email && phoneNumber && locale) {
setValidated(true);
}
if (validated) {
// If validated is true, send the request to the server, if the server's response is successful load next page, if not then an error page is loaded
console.log('Performing');
axios
.post('http://localhost:8000/api/v1/orders', {
firstName,
lastName,
email,
phone: phoneNumber,
locale,
outsideCanada,
cart: props.cart.items,
})
.then(function (res) {
// If response is not an error setResponse
if (res.data.status === 'success') {
// Set response message to true
setResponse(true);
// Reset Cart If Successful
props.setCart(new Cart());
} else if (
res.data.status === 'fail' ||
res.data.status !== 'success'
) {
console.log(res);
// Throw error so that it will be caught in the catch block
// throw new Error(res.data.message);
}
})
.catch((err) => {
console.log(err);
setResponse(true);
setError(true);
});
}
};
解决方案
我认为问题可能出在这个地方..
if (firstName && lastName && email && phoneNumber && locale) {
setValidated(true);
}
if (validated) {
请记住,setValidator是一个异步函数,您不能在调用它后立即依赖它们的值。您有两个选择,要么更改 if 语句,要么添加一个 useEffect 挂钩来侦听确认的更改。
if (firstName && lastName && email && phoneNumber && locale) {
setValidated(true);
// call axios here
}
或者
useEffect( () => { // this function is called only after "validated" state change
if( validated ) {
// call axios here
}
}, [validated])
推荐阅读
- mysql - 仅当通过 bash 脚本文件在 mysql 表中存在列时才编写更新查询
- azure - 如果浏览器选项卡处于非活动状态,则 SignalR 连接超时
- java - Java 将 Byte[] 转换为 Blob
- r - 我应该使用什么 GLM 来尝试和控制努力?
- javascript - 如何在日期对象中使用 24 小时格式?
- nativescript-angular - 在 nativescript-angular 应用程序中永远不会触发 Firebase 身份验证更改侦听器
- android - Android 启动带有确切地址的逐向导航意图
- python - 将行插入 MySQL 表时出现 pymysql.err.ProgrammingError 错误(使用 Python、Flask、ClearDB)
- algorithm - 如何找到堆的第k个元素
- elasticsearch - Elasticsearch - 优化聚合而不计算?