首页 > 解决方案 > 按钮组件需要两次点击

问题描述

我的网站上有一个发货表单部分,最后有一个按钮,它应该获取表单的值并将这些数据发布到我的后端服务器,但是每当我第一次单击时没有任何效果,它只能工作在第二次点击时。

这是我的自定义按钮组件

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);
        });
    }
  };

标签: javascriptreactjs

解决方案


我认为问题可能出在这个地方..

    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]) 

推荐阅读