再次打开文档后切换复选框未选中

问题描述 投票:0回答:1

我是 React 新手,我有一个引导开关复选框,对我来说,该值保存在 mongodb 中,但我的问题是当我再次打开文档时,该复选框不在上次更新的位置。

如果我更新了文档,而事实确实如此,那就不会了

enter image description here

代码如下:

  const [flag, setFlag] = useState(false);
  
  const checkHandler = () => {
    setFlag(!flag);
  };

  useEffect(() => {
    if (order) {
      console.log("order is present in empty useEffect", order);
      setFlag(order.flag);
    }
  }, [order]);
<div className="flagOrder">
                    <div class="form-check form-switch">
                      <input
                        class="form-check-input"
                        type="checkbox"
                        role="switch"
                        id="flexSwitchCheckDefault"
                        checked={flag}
                        onChange={checkHandler}
                      />
                      <label
                        class="form-check-label"
                        for="flexSwitchCheckDefault"
                      >
                        Flag
                      </label>
                    </div>
                  </div>

单击页面上的更新订单按钮时运行以下函数

const updateOrder = (order, items) => {
    console.log("ofasdfrder in update order", order);
    const updatedata = {
      _id: order._id,
      items: items,
      customerNotes:
        newCustomerNote.length > 0
          ? [...customerNotes, { notes: newCustomerNote, user: user._id }]
          : customerNotes,
      internalNotes:
        newInternalNote.length > 0
          ? [...internalNotes, { notes: newInternalNote, user: user._id }]
          : internalNotes,
      paymentMade: partialPaymentMade,
      newCustomerNote: newCustomerNote,
      newInternalNote: newInternalNote,
      paymentStatus: paymentStatus,
      changePaymentStatus:
        originalPaymentStatus === paymentStatus ? true : false,
      sendToCustomerNotes: sendToCustomerNotes,
      sendToInternalNotes: sendToInternalNotes,
      subTotal: getSubTotal(items).toFixed(2),
      totalAmount: (
        getSubTotal(items) +
        getTax(items) +
        getShipping(items)
      ).toFixed(2),
      shippingTotal: order ? getShipping(items) : 0,
      taxTotal: getTax(items),
      orderStatus: orderStatus,
      flag: flag,
    };

javascript reactjs mongodb react-hooks checkbox
1个回答
0
投票

我认为您需要在页面加载时检查存储在 mongoDB 中的值以检查复选框的状态。如果那里缺少,请加载默认状态。

© www.soinside.com 2019 - 2024. All rights reserved.