【问题标题】:React Popup not showing correctlyReact Popup 未正确显示
【发布时间】:2020-06-24 03:45:26
【问题描述】:

0

我在 React 中使用 useState 时遇到了一些问题。我有一个自定义组件Dialog,它可以传递renderAction 和renderContent 作为道具。

所以我设法打开了第一个对话框,一切看起来都井井有条,这是代码底部的<Dialog> 标签。但是在我从服务器得到响应后,我想显示第二个 Dialog 弹出窗口并关闭第一个 Dialog 弹出窗口。但在第一个消失后,第二个永远不会弹出。

服务器调用成功,所以response.success为真,这就是为什么setPopupOpen=false(关闭第一个弹出窗口)有效,但我不知道为什么,因为我设置了secondPopupOpen=true,但为什么同样的方法将无法显示第二个对话框弹出窗口。

AppNav.js

const AppNav = () => {
    //...
    const [popupOpen, setPopupOpen] = useState(false);
    const [secondPopupOpen, setSecondPopupOpen] = useState(false);
    const [input, setInput] = useState('');

const renderContent = () => { 
  return ( 
    <form>
     <input
      type="text"
      onChange={e => setInput(e.target.value)}
      value={input}
      onBlur={() =>delay(() =>setInput(''),150}
      placeholder='placeholder here...'
     />
    </form>
  );
};

const renderAction = () => { 
  const handleSubmit = async() => {
    //some server calls here
    // response is what got back from server call
  try{
    if(response.success){
      setPopupOpen(false);
      setSecondPopupOpen(true);
      return (
       <
        <Dialog
         open={secondPopupOpen}
         renderContent={() => <span>Message:</span>}
         renderAction={() => <span>operation successful!</span>}
     />
    )
   }
  }
  return ( 
    <Button onClick={handleSubmit}>Submit</Button>
  );
};
  return (
   <Dialog
     open={popupOpen}
     renderContent={RenderContent}
     renderAction={RenderAction}
   />
  )
}

【问题讨论】:

  • 能否提供该组件的沙箱链接或完整代码?

标签: javascript html reactjs async-await react-hooks


【解决方案1】:

您不需要两个Dialog 组件。您在handleSubmit 中的Dialog 不起作用的原因是它没有返回到功能组件,仅返回到handleSubmit 函数。

您可以做到这一点的一种方法是将renderContent 和renderAction 保存在状态中,并将其传递给组件中返回的Dialog(在文件末尾)。

但是,您不想将 JSX 存储在状态中。尝试仅保存您想在状态中显示的文本,例如 Message 而不是 &lt;span&gt;{Message}&lt;/span&gt;

【讨论】:

    【解决方案2】:

    只需从句柄提交中删除返回语句,然后在第一个对话框下方添加第二个对话框,如下所示。

    return (
      <>
       <Dialog
         open={popupOpen}
         renderContent={RenderContent}
         renderAction={RenderAction}
       />
       <Dialog
         open={secondPopupOpen}
         renderContent={() => <span>Message:</span>}
         renderAction={() => <span>operation successful!</span>}
         />
      </>
    )
    

    之前您的第二个对话框没有显示,有两个可能的原因。
    第一个可能是因为您将其返回到第一个对话框的 renderAction,并且第一个对话框在该时间点关闭。
    第二个是 setState 是 asynchronous 所以它可能会在将 secondPopupOpen 设置为 true 之前返回。

    【讨论】:

    • 感谢您的帮助,但它似乎仍然无法正常工作:(您认为我需要将 setSecondPopupOpen 放在哪里?
    • 您正确设置了setSecondPopupOpen,您只需要删除句柄提交中的return语句。你能告诉那个对话框来自哪里,这意味着你使用的是哪个包/库?
    猜你喜欢
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-01
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    相关资源
    最近更新 更多