反应挂钩:将状态设置为“ ModalVisible”,但状态不会立即更新

时间:2020-03-03 15:05:54

标签: javascript reactjs react-hooks antd

我使用setModalConfirmVisible(true),但是状态modalConfirmVisible不会立即更新。因此,模态不会显示。

如何立即更新此状态?

See happened 当我单击“删除”按钮时。控制台将仅显示来自

的false

console.log(modalConfirmVisible)

  useEffect(() => {
    (async () => {
      try {
        setFetchLoading(true)
        setTransactions(await fetchTransactions())
        setFetchLoading(false)
      } catch (err) {
        console.error(err)
      }
    })()
  }, [modalConfirmVisible])

  async function handleRemoveTransaction(id) {
    setRemoveLoading(true)
    setModalConfirmVisible(true)
    console.log(modalConfirmVisible)
    await handleConfirmRemoveTransaction(true, id)
  }


  return (
    {modalConfirmVisible && (
      <ModalConfirm
        onConfirmRemove={handleConfirmRemoveTransaction}
        onCancel={() => setModalConfirmVisible(false)}
        visible={true} 
      />
    )}
  )


// ModalConfirm.js
const ModalConfirm = ({ onConfirmRemove, visible }) => {
  return (
    <Modal
      visible={visible}
      title="Do you want to delete these items?"
      icon={<ExclamationCircleOutlined />}
      content="When clicked the OK button, this dialog will be closed after 1 second"
      onOk={() => onConfirmRemove(true)}
      onCancel={() => onConfirmRemove(false)}
    />
  )
}

2 个答案:

答案 0 :(得分:1)

您应该尝试从处理确认中分离出打开模式的逻辑。这样,状态更新就可以在modalConfirmVisible可以打开的下一个渲染周期设置confirmModal then

// from component in screen cap click remove, just open the modal
function openRemoveConfirmation() {
  setRemoveLoading(true)
  setModalConfirmVisible(true)
}

// handle confirmation separately
function handleRemoveTransaction(id) {
  handleConfirmRemoveTransaction(true, id)
}

return (
  {modalConfirmVisible && (
    <ModalConfirm
      onConfirmRemove={handleConfirmRemoveTransaction}
      onCancel={() => setModalConfirmVisible(false)}
      visible={true} 
    />
  )}
)

答案 1 :(得分:0)

因为您使用的是反应钩,所以请立即更改任何state

正确的方法是在下一个cycle中检查modalConfirmVisible的值。并且由于您setState并且状态已更改,因此该函数将再次执行:

const [modalConfirmVisible, setModalConfirmVisible] = useState(false);

async function handleRemoveTransaction(id) {
  setRemoveLoading(true)
  setModalConfirmVisible(true)
  await handleConfirmRemoveTransaction(true, id)
}
console.log(modalConfirmVisible)