我试图将response
消息从服务器传递回并显示在UI中,但是似乎每当我在第二个response
中传递<Dialog>
时,响应都是不确定的,我认为response
仅在处理提交功能中定义。
有没有办法将response
传递到<Dialog>
?
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
const response = await service.send(request)
try{
if(response.result ==='success'){
setPopupOpen(false);
setSecondPopupOpen(true);
}else { throw new Error()}
}
catch (err) {throw new Error()}
return response;
}
return (
<Button onClick={handleSubmit}>Submit</Button>
);
};
//...
return (
<Button onClick={() => setPopupOpen(true)}>open button</Button>
<Dialog
open={popupOpen}
renderContent={renderContent}
renderAction={renderAction}
/>
<Dialog
open={secondPopupOpen}
renderContent={(response) => <span><>{response.resultMessage}</span>}
renderAction={() => {}}
/>
)
}
Dialog.js
const Dialog = props => {
const { renderAction, renderContent, renderTitle} = props;
return (
render={
({getTitleProps, getContentProps, getActionProps}) => (
<DialogTitle {...getTitleProps()}>
{renderTitle ? renderTitle() : <span>Title</span>}
</DialogTitle>
<DialogContent {...getContentProps()}>
{renderContent ? renderContent() : <span>Content</span>}
</DialogContent>
<DialogAction {...getActionProps()}>
{renderAction ? renderAction() : <span>Action</span>}
</DialogAction>
)
}
)
}
答案 0 :(得分:1)
我认为您应该重构renderAction
函数并将请求的状态以及错误(或将它们组合成一个状态)存储在某个地方。
const [response, setResponse] = useState(null);
const [error, setError] = useState(null);
const handleSubmit = async() => {
const response = await service.send(request)
try {
if(response.result ==='success'){
setPopupOpen(false);
setSecondPopupOpen(true);
setResponse(response);
return;
}
setError(new Error('error'));
}
catch (error) {
setError(error);
}
}
const renderAction = () => {
if(response) {
return response;
}
if(error) {
return error.message // to-do
}
return <Button onClick={handleSubmit}>Submit</Button>
};