我在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}
/>
)
}
发布于 2020-06-24 11:55:29
您不需要两个Dialog
组件。handleSubmit
中的Dialog
不起作用的原因是它没有返回给功能组件,而只是返回给了handleSubmit
函数。
一种方法是保存状态上的renderContent
和renderAction
,并将其传递给组件中返回的Dialog
(在文件的末尾)。
但是,您不希望将JSX存储在状态中。尝试仅保存您希望在状态中显示的文本,如Message
而不是<span>{Message}</span>
发布于 2020-06-24 12:06:25
只需从handle submit中删除返回语句,并在第一个对话框下面添加第二个对话框,如下所示。
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之前返回。
https://stackoverflow.com/questions/62547267
复制相似问题